virsh.c 615.2 KB
Newer Older
1
/*
2
 * virsh.c: a shell to exercise the libvirt API
3
 *
4
 * Copyright (C) 2005, 2007-2012 Red Hat, Inc.
5 6 7 8
 *
 * See COPYING.LIB for the License of this software
 *
 * Daniel Veillard <veillard@redhat.com>
K
Karel Zak 已提交
9
 * Karel Zak <kzak@redhat.com>
K
Karel Zak 已提交
10
 * Daniel P. Berrange <berrange@redhat.com>
11 12
 */

13
#include <config.h>
14

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

38 39 40
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
41
#include <libxml/xmlsave.h>
42

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

48
#include "internal.h"
49
#include "virterror_internal.h"
50
#include "base64.h"
51
#include "buf.h"
52
#include "console.h"
53
#include "util.h"
54
#include "memory.h"
55
#include "xml.h"
56
#include "libvirt/libvirt-qemu.h"
E
Eric Blake 已提交
57
#include "virfile.h"
58
#include "event_poll.h"
59
#include "configmake.h"
60
#include "threads.h"
E
Eric Blake 已提交
61
#include "command.h"
62
#include "virkeycode.h"
63
#include "virnetdevbandwidth.h"
64
#include "util/bitmap.h"
H
Hu Tao 已提交
65
#include "conf/domain_conf.h"
66
#include "virtypedparam.h"
67 68
#include "intprops.h"
#include "conf/virdomainlist.h"
K
Karel Zak 已提交
69 70 71

static char *progname;

72 73
#define VIRSH_MAX_XML_FILE 10*1024*1024

K
Karel Zak 已提交
74 75 76
#define VSH_PROMPT_RW    "virsh # "
#define VSH_PROMPT_RO    "virsh > "

77 78
#define VIR_FROM_THIS VIR_FROM_NONE

K
Karel Zak 已提交
79 80 81 82 83
#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)

84 85 86
/* Default escape char Ctrl-] as per telnet */
#define CTRL_CLOSE_BRACKET "^]"

87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
/**
 * 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:
 *
J
Jim Meyering 已提交
104
 * Indicates the level of a log message
105 106 107 108 109 110 111 112 113
 */
typedef enum {
    VSH_ERR_DEBUG = 0,
    VSH_ERR_INFO,
    VSH_ERR_NOTICE,
    VSH_ERR_WARNING,
    VSH_ERR_ERROR
} vshErrorLevel;

J
Jiri Denemark 已提交
114 115
#define VSH_DEBUG_DEFAULT VSH_ERR_ERROR

K
Karel Zak 已提交
116 117 118 119 120
/*
 * virsh command line grammar:
 *
 *    command_line    =     <command>\n | <command>; <command>; ...
 *
E
Eric Blake 已提交
121
 *    command         =    <keyword> <option> [--] <data>
K
Karel Zak 已提交
122 123 124 125 126
 *
 *    option          =     <bool_option> | <int_option> | <string_option>
 *    data            =     <string>
 *
 *    bool_option     =     --optionname
E
Eric Blake 已提交
127 128
 *    int_option      =     --optionname <number> | --optionname=<number>
 *    string_option   =     --optionname <string> | --optionname=<string>
129
 *
E
Eric Blake 已提交
130
 *    keyword         =     [a-zA-Z][a-zA-Z-]*
131
 *    number          =     [0-9]+
E
Eric Blake 已提交
132
 *    string          =     ('[^']*'|"([^\\"]|\\.)*"|([^ \t\n\\'"]|\\.))+
K
Karel Zak 已提交
133 134 135 136
 *
 */

/*
137
 * vshCmdOptType - command option type
138
 */
K
Karel Zak 已提交
139
typedef enum {
140 141 142
    VSH_OT_BOOL,     /* optional boolean option */
    VSH_OT_STRING,   /* optional string option */
    VSH_OT_INT,      /* optional or mandatory int option */
143
    VSH_OT_DATA,     /* string data (as non-option) */
E
Eric Blake 已提交
144 145
    VSH_OT_ARGV,     /* remaining arguments */
    VSH_OT_ALIAS,    /* alternate spelling for a later argument */
K
Karel Zak 已提交
146 147
} vshCmdOptType;

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
/*
 * Command group types
 */
#define VSH_CMD_GRP_DOM_MANAGEMENT   "Domain Management"
#define VSH_CMD_GRP_DOM_MONITORING   "Domain Monitoring"
#define VSH_CMD_GRP_STORAGE_POOL     "Storage Pool"
#define VSH_CMD_GRP_STORAGE_VOL      "Storage Volume"
#define VSH_CMD_GRP_NETWORK          "Networking"
#define VSH_CMD_GRP_NODEDEV          "Node Device"
#define VSH_CMD_GRP_IFACE            "Interface"
#define VSH_CMD_GRP_NWFILTER         "Network Filter"
#define VSH_CMD_GRP_SECRET           "Secret"
#define VSH_CMD_GRP_SNAPSHOT         "Snapshot"
#define VSH_CMD_GRP_HOST_AND_HV      "Host and Hypervisor"
#define VSH_CMD_GRP_VIRSH            "Virsh itself"

K
Karel Zak 已提交
164 165 166
/*
 * Command Option Flags
 */
E
Eric Blake 已提交
167 168 169 170
enum {
    VSH_OFLAG_NONE     = 0,        /* without flags */
    VSH_OFLAG_REQ      = (1 << 0), /* option required */
    VSH_OFLAG_EMPTY_OK = (1 << 1), /* empty string option allowed */
L
Lai Jiangshan 已提交
171
    VSH_OFLAG_REQ_OPT  = (1 << 2), /* --optionname required */
E
Eric Blake 已提交
172
};
K
Karel Zak 已提交
173 174 175 176 177 178

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

/*
E
Eric Blake 已提交
179 180 181 182 183
 * vshCmdInfo -- name/value pair for information about command
 *
 * Commands should have at least the following names:
 * "name" - command name
 * "desc" - description of command, or empty string
K
Karel Zak 已提交
184
 */
185
typedef struct {
E
Eric Blake 已提交
186 187
    const char *name;           /* name of information, or NULL for list end */
    const char *data;           /* non-NULL information */
K
Karel Zak 已提交
188 189 190 191 192
} vshCmdInfo;

/*
 * vshCmdOptDef - command option definition
 */
193
typedef struct {
E
Eric Blake 已提交
194
    const char *name;           /* the name of option, or NULL for list end */
195
    vshCmdOptType type;         /* option type */
E
Eric Blake 已提交
196
    unsigned int flags;         /* flags */
E
Eric Blake 已提交
197 198
    const char *help;           /* non-NULL help string; or for VSH_OT_ALIAS
                                 * the name of a later public option */
K
Karel Zak 已提交
199 200 201 202
} vshCmdOptDef;

/*
 * vshCmdOpt - command options
E
Eric Blake 已提交
203 204 205
 *
 * After parsing a command, all arguments to the command have been
 * collected into a list of these objects.
K
Karel Zak 已提交
206 207
 */
typedef struct vshCmdOpt {
E
Eric Blake 已提交
208 209
    const vshCmdOptDef *def;    /* non-NULL pointer to option definition */
    char *data;                 /* allocated data, or NULL for bool option */
210
    struct vshCmdOpt *next;
K
Karel Zak 已提交
211 212
} vshCmdOpt;

213 214 215 216 217
/*
 * Command Usage Flags
 */
enum {
    VSH_CMD_FLAG_NOCONNECT = (1 << 0),  /* no prior connection needed */
218
    VSH_CMD_FLAG_ALIAS     = (1 << 1),  /* command is an alias */
219 220
};

K
Karel Zak 已提交
221 222 223
/*
 * vshCmdDef - command definition
 */
224
typedef struct {
E
Eric Blake 已提交
225
    const char *name;           /* name of command, or NULL for list end */
E
Eric Blake 已提交
226
    bool (*handler) (vshControl *, const vshCmd *);    /* command handler */
227 228
    const vshCmdOptDef *opts;   /* definition of command options */
    const vshCmdInfo *info;     /* details about command */
229
    unsigned int flags;         /* bitwise OR of VSH_CMD_FLAG */
K
Karel Zak 已提交
230 231 232 233 234 235
} vshCmdDef;

/*
 * vshCmd - parsed command
 */
typedef struct __vshCmd {
236
    const vshCmdDef *def;       /* command definition */
237 238
    vshCmdOpt *opts;            /* list of command arguments */
    struct __vshCmd *next;      /* next command */
K
Karel Zak 已提交
239 240 241 242 243 244
} __vshCmd;

/*
 * vshControl
 */
typedef struct __vshControl {
K
Karel Zak 已提交
245
    char *name;                 /* connection name */
246
    virConnectPtr conn;         /* connection to hypervisor (MAY BE NULL) */
247 248
    vshCmd *cmd;                /* the current command */
    char *cmdstr;               /* string with command */
E
Eric Blake 已提交
249 250
    bool imode;                 /* interactive mode? */
    bool quiet;                 /* quiet mode */
251
    int debug;                  /* print debug messages? */
E
Eric Blake 已提交
252 253
    bool timing;                /* print timing info? */
    bool readonly;              /* connect readonly (first time only, not
254 255
                                 * during explicit connect command)
                                 */
256 257
    char *logfile;              /* log file name */
    int log_fd;                 /* log file descriptor */
258 259
    char *historydir;           /* readline history directory name */
    char *historyfile;          /* readline history file name */
260 261
    bool useGetInfo;            /* must use virDomainGetInfo, since
                                   virDomainGetState is not supported */
262 263
    bool useSnapshotOld;        /* cannot use virDomainSnapshotGetParent or
                                   virDomainSnapshotNumChildren */
J
Jiri Denemark 已提交
264
    virThread eventLoop;
265
    virMutex lock;
J
Jiri Denemark 已提交
266 267
    bool eventLoopStarted;
    bool quit;
268 269 270

    const char *escapeChar;     /* String representation of
                                   console escape character */
K
Karel Zak 已提交
271
} __vshControl;
272

273
typedef struct vshCmdGrp {
E
Eric Blake 已提交
274
    const char *name;    /* name of group, or NULL for list end */
275 276 277
    const char *keyword; /* help keyword */
    const vshCmdDef *commands;
} vshCmdGrp;
278

279
static const vshCmdGrp cmdGroups[];
K
Karel Zak 已提交
280

281 282
static void vshError(vshControl *ctl, const char *format, ...)
    ATTRIBUTE_FMT_PRINTF(2, 3);
E
Eric Blake 已提交
283 284
static bool vshInit(vshControl *ctl);
static bool vshDeinit(vshControl *ctl);
285
static void vshUsage(void);
286
static void vshOpenLogFile(vshControl *ctl);
287 288
static void vshOutputLogFile(vshControl *ctl, int log_level, const char *format, va_list ap)
    ATTRIBUTE_FMT_PRINTF(3, 0);
289
static void vshCloseLogFile(vshControl *ctl);
K
Karel Zak 已提交
290

E
Eric Blake 已提交
291
static bool vshParseArgv(vshControl *ctl, int argc, char **argv);
K
Karel Zak 已提交
292

293
static const char *vshCmddefGetInfo(const vshCmdDef *cmd, const char *info);
294
static const vshCmdDef *vshCmddefSearch(const char *cmdname);
E
Eric Blake 已提交
295
static bool vshCmddefHelp(vshControl *ctl, const char *name);
296
static const vshCmdGrp *vshCmdGrpSearch(const char *grpname);
E
Eric Blake 已提交
297
static bool vshCmdGrpHelp(vshControl *ctl, const char *name);
K
Karel Zak 已提交
298

E
Eric Blake 已提交
299 300 301
static int vshCommandOpt(const vshCmd *cmd, const char *name, vshCmdOpt **opt)
    ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(3)
    ATTRIBUTE_RETURN_CHECK;
302 303
static int vshCommandOptInt(const vshCmd *cmd, const char *name, int *value)
    ATTRIBUTE_NONNULL(3) ATTRIBUTE_RETURN_CHECK;
304 305 306
static int vshCommandOptUInt(const vshCmd *cmd, const char *name,
                             unsigned int *value)
    ATTRIBUTE_NONNULL(3) ATTRIBUTE_RETURN_CHECK;
307 308 309 310 311 312 313 314 315
static int vshCommandOptUL(const vshCmd *cmd, const char *name,
                           unsigned long *value)
    ATTRIBUTE_NONNULL(3) ATTRIBUTE_RETURN_CHECK;
static int vshCommandOptString(const vshCmd *cmd, const char *name,
                               const char **value)
    ATTRIBUTE_NONNULL(3) ATTRIBUTE_RETURN_CHECK;
static int vshCommandOptLongLong(const vshCmd *cmd, const char *name,
                                 long long *value)
    ATTRIBUTE_NONNULL(3) ATTRIBUTE_RETURN_CHECK;
316 317 318
static int vshCommandOptULongLong(const vshCmd *cmd, const char *name,
                                  unsigned long long *value)
    ATTRIBUTE_NONNULL(3) ATTRIBUTE_RETURN_CHECK;
E
Eric Blake 已提交
319 320 321 322
static int vshCommandOptScaledInt(const vshCmd *cmd, const char *name,
                                  unsigned long long *value, int scale,
                                  unsigned long long max)
    ATTRIBUTE_NONNULL(3) ATTRIBUTE_RETURN_CHECK;
E
Eric Blake 已提交
323
static bool vshCommandOptBool(const vshCmd *cmd, const char *name);
324 325
static const vshCmdOpt *vshCommandOptArgv(const vshCmd *cmd,
                                          const vshCmdOpt *opt);
326 327 328
static char *vshGetDomainDescription(vshControl *ctl, virDomainPtr dom,
                                     bool title, unsigned int flags)
    ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2) ATTRIBUTE_RETURN_CHECK;
K
Karel Zak 已提交
329

330 331 332
#define VSH_BYID     (1 << 1)
#define VSH_BYUUID   (1 << 2)
#define VSH_BYNAME   (1 << 3)
333
#define VSH_BYMAC    (1 << 4)
K
Karel Zak 已提交
334

335
static virDomainPtr vshCommandOptDomainBy(vshControl *ctl, const vshCmd *cmd,
336
                                          const char **name, int flag);
K
Karel Zak 已提交
337 338

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

342
static virNetworkPtr vshCommandOptNetworkBy(vshControl *ctl, const vshCmd *cmd,
343
                                            const char **name, int flag);
344 345

/* default is lookup by Name and UUID */
J
Jim Meyering 已提交
346 347
#define vshCommandOptNetwork(_ctl, _cmd, _name)                    \
    vshCommandOptNetworkBy(_ctl, _cmd, _name,                      \
348 349
                           VSH_BYUUID|VSH_BYNAME)

350
static virNWFilterPtr vshCommandOptNWFilterBy(vshControl *ctl, const vshCmd *cmd,
351
                                                  const char **name, int flag);
352 353 354 355 356 357

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

358
static virInterfacePtr vshCommandOptInterfaceBy(vshControl *ctl, const vshCmd *cmd,
359
                                                const char *optname,
360
                                                const char **name, int flag);
361 362 363

/* default is lookup by Name and MAC */
#define vshCommandOptInterface(_ctl, _cmd, _name)                    \
364 365
    vshCommandOptInterfaceBy(_ctl, _cmd, NULL, _name,                \
                             VSH_BYMAC|VSH_BYNAME)
366

367
static virStoragePoolPtr vshCommandOptPoolBy(vshControl *ctl, const vshCmd *cmd,
368
                            const char *optname, const char **name, int flag);
369 370 371 372 373 374

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

375
static virStorageVolPtr vshCommandOptVolBy(vshControl *ctl, const vshCmd *cmd,
376 377
                                           const char *optname,
                                           const char *pooloptname,
378
                                           const char **name, int flag);
379 380

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

385
static virSecretPtr vshCommandOptSecret(vshControl *ctl, const vshCmd *cmd,
386
                                        const char **name);
387

388
static void vshPrintExtra(vshControl *ctl, const char *format, ...)
389
    ATTRIBUTE_FMT_PRINTF(2, 3);
390
static void vshDebug(vshControl *ctl, int level, const char *format, ...)
391
    ATTRIBUTE_FMT_PRINTF(3, 4);
K
Karel Zak 已提交
392 393

/* XXX: add batch support */
394
#define vshPrint(_ctl, ...)   vshPrintExtra(NULL, __VA_ARGS__)
K
Karel Zak 已提交
395

396
static int vshDomainState(vshControl *ctl, virDomainPtr dom, int *reason);
K
Karel Zak 已提交
397
static const char *vshDomainStateToString(int state);
398
static const char *vshDomainStateReasonToString(int state, int reason);
399
static const char *vshDomainControlStateToString(int state);
400
static const char *vshDomainVcpuStateToString(int state);
E
Eric Blake 已提交
401
static bool vshConnectionUsability(vshControl *ctl, virConnectPtr conn);
402 403 404
static virTypedParameterPtr vshFindTypedParamByName(const char *name,
                                                    virTypedParameterPtr list,
                                                    int count);
405 406
static char *vshGetTypedParamValue(vshControl *ctl, virTypedParameterPtr item)
    ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2);
K
Karel Zak 已提交
407

E
Eric Blake 已提交
408 409 410
static char *editWriteToTempFile(vshControl *ctl, const char *doc);
static int   editFile(vshControl *ctl, const char *filename);
static char *editReadBackFile(vshControl *ctl, const char *filename);
411

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
/* Typedefs, function prototypes for job progress reporting.
 * There are used by some long lingering commands like
 * migrate, dump, save, managedsave.
 */
typedef struct __vshCtrlData {
    vshControl *ctl;
    const vshCmd *cmd;
    int writefd;
} vshCtrlData;

typedef void (*jobWatchTimeoutFunc) (vshControl *ctl, virDomainPtr dom,
                                     void *opaque);

static bool
vshWatchJob(vshControl *ctl,
            virDomainPtr dom,
            bool verbose,
            int pipe_fd,
            int timeout,
            jobWatchTimeoutFunc timeout_func,
            void *opaque,
            const char *label);

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

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

441
static char *_vshStrdup(vshControl *ctl, const char *s, const char *filename, int line);
442 443
#define vshStrdup(_ctl, _s)    _vshStrdup(_ctl, _s, __FILE__, __LINE__)

444 445
static int parseRateStr(const char *rateStr, virNetDevBandwidthRatePtr rate);

E
Eric Blake 已提交
446 447 448
static void *
_vshMalloc(vshControl *ctl, size_t size, const char *filename, int line)
{
E
Eric Blake 已提交
449
    char *x;
E
Eric Blake 已提交
450

E
Eric Blake 已提交
451
    if (VIR_ALLOC_N(x, size) == 0)
E
Eric Blake 已提交
452 453 454 455 456 457 458 459 460
        return x;
    vshError(ctl, _("%s: %d: failed to allocate %d bytes"),
             filename, line, (int) size);
    exit(EXIT_FAILURE);
}

static void *
_vshCalloc(vshControl *ctl, size_t nmemb, size_t size, const char *filename, int line)
{
E
Eric Blake 已提交
461
    char *x;
E
Eric Blake 已提交
462

E
Eric Blake 已提交
463 464
    if (!xalloc_oversized(nmemb, size) &&
        VIR_ALLOC_N(x, nmemb * size) == 0)
E
Eric Blake 已提交
465 466 467 468 469 470 471 472 473 474 475 476
        return x;
    vshError(ctl, _("%s: %d: failed to allocate %d bytes"),
             filename, line, (int) (size*nmemb));
    exit(EXIT_FAILURE);
}

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

    if (s == NULL)
477
        return NULL;
E
Eric Blake 已提交
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
    if ((x = strdup(s)))
        return x;
    vshError(ctl, _("%s: %d: failed to allocate %lu bytes"),
             filename, line, (unsigned long)strlen(s));
    exit(EXIT_FAILURE);
}

/* Poison the raw allocating identifiers in favor of our vsh variants.  */
#undef malloc
#undef calloc
#undef realloc
#undef strdup
#define malloc use_vshMalloc_instead_of_malloc
#define calloc use_vshCalloc_instead_of_calloc
#define realloc use_vshRealloc_instead_of_realloc
#define strdup use_vshStrdup_instead_of_strdup
494

495 496 497 498 499
static int
vshNameSorter(const void *a, const void *b)
{
    const char **sa = (const char**)a;
    const char **sb = (const char**)b;
500

501 502
    /* User visible sort, so we want locale-specific case comparison. */
    return strcasecmp(*sa, *sb);
503 504
}

505 506 507 508 509 510 511
static double
prettyCapacity(unsigned long long val,
               const char **unit) {
    if (val < 1024) {
        *unit = "";
        return (double)val;
    } else if (val < (1024.0l * 1024.0l)) {
512
        *unit = "KiB";
513 514
        return (((double)val / 1024.0l));
    } else if (val < (1024.0l * 1024.0l * 1024.0l)) {
515
        *unit = "MiB";
516
        return (double)val / (1024.0l * 1024.0l);
517
    } else if (val < (1024.0l * 1024.0l * 1024.0l * 1024.0l)) {
518
        *unit = "GiB";
519
        return (double)val / (1024.0l * 1024.0l * 1024.0l);
520
    } else {
521
        *unit = "TiB";
522
        return (double)val / (1024.0l * 1024.0l * 1024.0l * 1024.0l);
523 524 525 526
    }
}


J
John Levon 已提交
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
static virErrorPtr last_error;

/*
 * Quieten libvirt until we're done with the command.
 */
static void
virshErrorHandler(void *unused ATTRIBUTE_UNUSED, virErrorPtr error)
{
    virFreeError(last_error);
    last_error = virSaveLastError();
    if (getenv("VIRSH_DEBUG") != NULL)
        virDefaultErrorFunc(error);
}

/*
 * Report an error when a command finishes.  This is better than before
 * (when correct operation would report errors), but it has some
 * problems: we lose the smarter formatting of virDefaultErrorFunc(),
 * and it can become harder to debug problems, if errors get reported
 * twice during one command.  This case shouldn't really happen anyway,
 * and it's IMHO a bug that libvirt does that sometimes.
 */
static void
virshReportError(vshControl *ctl)
{
552 553 554 555 556 557 558 559
    if (last_error == NULL) {
        /* Calling directly into libvirt util functions won't trigger the
         * error callback (which sets last_error), so check it ourselves.
         *
         * If the returned error has CODE_OK, this most likely means that
         * no error was ever raised, so just ignore */
        last_error = virSaveLastError();
        if (!last_error || last_error->code == VIR_ERR_OK)
560
            goto out;
561
    }
J
John Levon 已提交
562 563

    if (last_error->code == VIR_ERR_OK) {
564
        vshError(ctl, "%s", _("unknown error"));
J
John Levon 已提交
565 566 567
        goto out;
    }

568
    vshError(ctl, "%s", last_error->message);
J
John Levon 已提交
569 570 571 572 573 574

out:
    virFreeError(last_error);
    last_error = NULL;
}

575 576 577 578 579 580 581 582 583
static volatile sig_atomic_t intCaught = 0;

static void vshCatchInt(int sig ATTRIBUTE_UNUSED,
                        siginfo_t *siginfo ATTRIBUTE_UNUSED,
                        void *context ATTRIBUTE_UNUSED)
{
    intCaught = 1;
}

584 585 586 587 588
/*
 * Detection of disconnections and automatic reconnection support
 */
static int disconnected = 0; /* we may have been disconnected */

589 590 591 592 593
/* Gnulib doesn't guarantee SA_SIGINFO support.  */
#ifndef SA_SIGINFO
# define SA_SIGINFO 0
#endif

594 595 596 597 598 599
/*
 * vshCatchDisconnect:
 *
 * We get here when a SIGPIPE is being raised, we can't do much in the
 * handler, just save the fact it was raised
 */
600 601
static void vshCatchDisconnect(int sig, siginfo_t *siginfo,
                               void *context ATTRIBUTE_UNUSED) {
E
Eric Blake 已提交
602
    if (sig == SIGPIPE ||
603
        (SA_SIGINFO && siginfo->si_signo == SIGPIPE))
604 605 606 607 608 609 610 611 612
        disconnected++;
}

/*
 * vshSetupSignals:
 *
 * Catch SIGPIPE signals which may arise when disconnection
 * from libvirtd occurs
 */
L
Laine Stump 已提交
613
static void
614 615 616 617 618 619 620 621 622 623 624 625 626
vshSetupSignals(void) {
    struct sigaction sig_action;

    sig_action.sa_sigaction = vshCatchDisconnect;
    sig_action.sa_flags = SA_SIGINFO;
    sigemptyset(&sig_action.sa_mask);

    sigaction(SIGPIPE, &sig_action, NULL);
}

/*
 * vshReconnect:
 *
L
Laine Stump 已提交
627
 * Reconnect after a disconnect from libvirtd
628 629
 *
 */
L
Laine Stump 已提交
630
static void
631 632 633 634 635 636
vshReconnect(vshControl *ctl)
{
    bool connected = false;

    if (ctl->conn != NULL) {
        connected = true;
637
        virConnectClose(ctl->conn);
638
    }
639 640 641 642 643 644

    ctl->conn = virConnectOpenAuth(ctl->name,
                                   virConnectAuthPtrDefault,
                                   ctl->readonly ? VIR_CONNECT_RO : 0);
    if (!ctl->conn)
        vshError(ctl, "%s", _("Failed to reconnect to the hypervisor"));
645
    else if (connected)
646 647
        vshError(ctl, "%s", _("Reconnected to the hypervisor"));
    disconnected = 0;
648
    ctl->useGetInfo = false;
649
    ctl->useSnapshotOld = false;
650
}
651

652
#ifndef WIN32
653 654 655 656 657 658 659 660 661 662 663 664 665
static void
vshPrintRaw(vshControl *ctl, ...)
{
    va_list ap;
    char *key;

    va_start(ap, ctl);
    while ((key = va_arg(ap, char *)) != NULL) {
        vshPrint(ctl, "%s\r\n", key);
    }
    va_end(ap);
}

666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
/**
 * vshAskReedit:
 * @msg: Question to ask user
 *
 * Ask user if he wants to return to previously
 * edited file.
 *
 * Returns 'y' if he wants to
 *         'f' if he forcibly wants to
 *         'n' if he doesn't want to
 *         -1  on error
 *          0  otherwise
 */
static int
vshAskReedit(vshControl *ctl, const char *msg)
{
    int c = -1;
    struct termios ttyattr;

    if (!isatty(STDIN_FILENO))
        return -1;

    virshReportError(ctl);

    if (vshMakeStdinRaw(&ttyattr, false) < 0)
        return -1;

    while (true) {
        /* TRANSLATORS: For now, we aren't using LC_MESSAGES, and the user
         * choices really are limited to just 'y', 'n', 'f' and '?'  */
        vshPrint(ctl, "\r%s %s", msg, _("Try again? [y,n,f,?]:"));
        c = c_tolower(getchar());

        if (c == '?') {
700 701 702 703 704 705 706
            vshPrintRaw(ctl,
                        "",
                        _("y - yes, start editor again"),
                        _("n - no, throw away my changes"),
                        _("f - force, try to redefine again"),
                        _("? - print this help"),
                        NULL);
707 708 709 710 711 712 713 714 715 716
            continue;
        } else if (c == 'y' || c == 'n' || c == 'f') {
            break;
        }
    }

    tcsetattr(STDIN_FILENO, TCSAFLUSH, &ttyattr);

    vshPrint(ctl, "\r\n");
    return c;
717 718 719 720 721
}
#else /* WIN32 */
static int
vshAskReedit(vshControl *ctl, const char *msg ATTRIBUTE_UNUSED)
{
722 723 724 725
    vshDebug(ctl, VSH_ERR_WARNING, "%s", _("This function is not "
                                           "supported on WIN32 platform"));
    return 0;
}
726
#endif /* WIN32 */
727

K
Karel Zak 已提交
728 729 730 731 732 733
/* ---------------
 * Commands
 * ---------------
 */

/*
734
 * "help" command
K
Karel Zak 已提交
735
 */
736
static const vshCmdInfo info_help[] = {
737
    {"help", N_("print help")},
738 739
    {"desc", N_("Prints global help, command specific help, or help for a\n"
                "    group of related commands")},
740

741
    {NULL, NULL}
K
Karel Zak 已提交
742 743
};

744
static const vshCmdOptDef opts_help[] = {
745
    {"command", VSH_OT_DATA, 0, N_("Prints global help, command specific help, or help for a group of related commands")},
746
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
747 748
};

E
Eric Blake 已提交
749
static bool
750
cmdHelp(vshControl *ctl, const vshCmd *cmd)
751
 {
752
    const char *name = NULL;
753

754
    if (vshCommandOptString(cmd, "command", &name) <= 0) {
755
        const vshCmdGrp *grp;
756
        const vshCmdDef *def;
757

758 759 760 761 762 763
        vshPrint(ctl, "%s", _("Grouped commands:\n\n"));

        for (grp = cmdGroups; grp->name; grp++) {
            vshPrint(ctl, _(" %s (help keyword '%s'):\n"), grp->name,
                     grp->keyword);

764 765 766
            for (def = grp->commands; def->name; def++) {
                if (def->flags & VSH_CMD_FLAG_ALIAS)
                    continue;
767 768
                vshPrint(ctl, "    %-30s %s\n", def->name,
                         _(vshCmddefGetInfo(def, "help")));
769
            }
770 771 772 773

            vshPrint(ctl, "\n");
        }

E
Eric Blake 已提交
774
        return true;
775
    }
776

E
Eric Blake 已提交
777
    if (vshCmddefSearch(name)) {
778
        return vshCmddefHelp(ctl, name);
E
Eric Blake 已提交
779
    } else if (vshCmdGrpSearch(name)) {
780 781 782
        return vshCmdGrpHelp(ctl, name);
    } else {
        vshError(ctl, _("command or command group '%s' doesn't exist"), name);
E
Eric Blake 已提交
783
        return false;
K
Karel Zak 已提交
784 785 786
    }
}

787 788 789
/*
 * "autostart" command
 */
790
static const vshCmdInfo info_autostart[] = {
791
    {"help", N_("autostart a domain")},
792
    {"desc",
793
     N_("Configure a domain to be automatically started at boot.")},
794 795 796
    {NULL, NULL}
};

797
static const vshCmdOptDef opts_autostart[] = {
798 799
    {"domain",  VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"disable", VSH_OT_BOOL, 0, N_("disable autostarting")},
800 801 802
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
803
static bool
804
cmdAutostart(vshControl *ctl, const vshCmd *cmd)
805 806
{
    virDomainPtr dom;
807
    const char *name;
808 809
    int autostart;

810
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
811
        return false;
812

J
Jim Meyering 已提交
813
    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
E
Eric Blake 已提交
814
        return false;
815 816 817 818

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

    if (virDomainSetAutostart(dom, autostart) < 0) {
819
        if (autostart)
820
            vshError(ctl, _("Failed to mark domain %s as autostarted"), name);
821
        else
822
            vshError(ctl, _("Failed to unmark domain %s as autostarted"), name);
823
        virDomainFree(dom);
E
Eric Blake 已提交
824
        return false;
825 826
    }

827
    if (autostart)
828
        vshPrint(ctl, _("Domain %s marked as autostarted\n"), name);
829
    else
830
        vshPrint(ctl, _("Domain %s unmarked as autostarted\n"), name);
831

832
    virDomainFree(dom);
E
Eric Blake 已提交
833
    return true;
834 835
}

K
Karel Zak 已提交
836
/*
837
 * "connect" command
K
Karel Zak 已提交
838
 */
839
static const vshCmdInfo info_connect[] = {
840
    {"help", N_("(re)connect to hypervisor")},
841
    {"desc",
842
     N_("Connect to local hypervisor. This is built-in command after shell start up.")},
843
    {NULL, NULL}
K
Karel Zak 已提交
844 845
};

846
static const vshCmdOptDef opts_connect[] = {
E
Eric Blake 已提交
847 848
    {"name",     VSH_OT_DATA, VSH_OFLAG_EMPTY_OK,
     N_("hypervisor connection URI")},
849
    {"readonly", VSH_OT_BOOL, 0, N_("read-only connection")},
850
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
851 852
};

E
Eric Blake 已提交
853
static bool
854
cmdConnect(vshControl *ctl, const vshCmd *cmd)
855
{
E
Eric Blake 已提交
856
    bool ro = vshCommandOptBool(cmd, "readonly");
857
    const char *name = NULL;
858

K
Karel Zak 已提交
859
    if (ctl->conn) {
860 861 862
        int ret;
        if ((ret = virConnectClose(ctl->conn)) != 0) {
            vshError(ctl, _("Failed to disconnect from the hypervisor, %d leaked reference(s)"), ret);
E
Eric Blake 已提交
863
            return false;
K
Karel Zak 已提交
864 865 866
        }
        ctl->conn = NULL;
    }
867

868
    VIR_FREE(ctl->name);
869 870
    if (vshCommandOptString(cmd, "name", &name) < 0) {
        vshError(ctl, "%s", _("Please specify valid connection URI"));
E
Eric Blake 已提交
871
        return false;
872
    }
873
    ctl->name = vshStrdup(ctl, name);
K
Karel Zak 已提交
874

875
    ctl->useGetInfo = false;
876
    ctl->useSnapshotOld = false;
E
Eric Blake 已提交
877
    ctl->readonly = ro;
K
Karel Zak 已提交
878

879 880 881
    ctl->conn = virConnectOpenAuth(ctl->name, virConnectAuthPtrDefault,
                                   ctl->readonly ? VIR_CONNECT_RO : 0);

K
Karel Zak 已提交
882
    if (!ctl->conn)
883
        vshError(ctl, "%s", _("Failed to connect to the hypervisor"));
884

E
Eric Blake 已提交
885
    return !!ctl->conn;
K
Karel Zak 已提交
886 887
}

888 889
#ifndef WIN32

890
/*
891
 * "console" command
892
 */
893
static const vshCmdInfo info_console[] = {
894
    {"help", N_("connect to the guest console")},
895
    {"desc",
896
     N_("Connect the virtual serial console for the guest")},
897 898 899
    {NULL, NULL}
};

900
static const vshCmdOptDef opts_console[] = {
901
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
902
    {"devname", VSH_OT_STRING, 0, N_("character device name")},
903 904 905 906
    {"force", VSH_OT_BOOL, 0,
      N_("force console connection (disconnect already connected sessions)")},
    {"safe", VSH_OT_BOOL, 0,
      N_("only connect if safe console handling is supported")},
907 908 909
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
910
static bool
911 912 913
cmdRunConsole(vshControl *ctl, virDomainPtr dom,
              const char *name,
              unsigned int flags)
914
{
E
Eric Blake 已提交
915
    bool ret = false;
916
    int state;
917

918
    if ((state = vshDomainState(ctl, dom, NULL)) < 0) {
919 920 921 922
        vshError(ctl, "%s", _("Unable to get domain status"));
        goto cleanup;
    }

923
    if (state == VIR_DOMAIN_SHUTOFF) {
924 925 926 927
        vshError(ctl, "%s", _("The domain is not running"));
        goto cleanup;
    }

928 929 930 931 932
    if (!isatty(STDIN_FILENO)) {
        vshError(ctl, "%s", _("Cannot run interactive console without a controlling TTY"));
        goto cleanup;
    }

933
    vshPrintExtra(ctl, _("Connected to domain %s\n"), virDomainGetName(dom));
934
    vshPrintExtra(ctl, _("Escape character is %s\n"), ctl->escapeChar);
935
    fflush(stdout);
936
    if (vshRunConsole(dom, name, ctl->escapeChar, flags) == 0)
E
Eric Blake 已提交
937
        ret = true;
938 939

 cleanup:
940

941 942 943
    return ret;
}

E
Eric Blake 已提交
944
static bool
945 946 947
cmdConsole(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
E
Eric Blake 已提交
948
    bool ret = false;
949 950 951
    bool force = vshCommandOptBool(cmd, "force");
    bool safe = vshCommandOptBool(cmd, "safe");
    unsigned int flags = 0;
952
    const char *name = NULL;
953

954
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
955
        return false;
956 957

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
958
        return false;
959

960 961 962 963
    if (vshCommandOptString(cmd, "devname", &name) < 0) {
        vshError(ctl, "%s", _("Invalid devname"));
        goto cleanup;
    }
964

965 966 967 968 969 970
    if (force)
        flags |= VIR_DOMAIN_CONSOLE_FORCE;
    if (safe)
        flags |= VIR_DOMAIN_CONSOLE_SAFE;

    ret = cmdRunConsole(ctl, dom, name, flags);
971

972
cleanup:
973 974 975 976
    virDomainFree(dom);
    return ret;
}

977 978 979
#endif /* WIN32 */


K
Karel Zak 已提交
980 981 982
/*
 * "list" command
 */
983
static const vshCmdInfo info_list[] = {
984 985
    {"help", N_("list domains")},
    {"desc", N_("Returns list of domains.")},
986
    {NULL, NULL}
K
Karel Zak 已提交
987 988
};

989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 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 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
/* compare domains, pack NULLed ones at the end*/
static int
vshDomainSorter(const void *a, const void *b)
{
    virDomainPtr *da = (virDomainPtr *) a;
    virDomainPtr *db = (virDomainPtr *) b;
    unsigned int ida;
    unsigned int idb;
    unsigned int inactive = (unsigned int) -1;

    if (*da && !*db)
        return -1;

    if (!*da)
        return *db != NULL;

    ida = virDomainGetID(*da);
    idb = virDomainGetID(*db);

    if (ida == inactive && idb == inactive)
        return strcasecmp(virDomainGetName(*da), virDomainGetName(*db));

    if (ida != inactive && idb != inactive) {
        if (ida > idb)
            return 1;
        else if (ida < idb)
            return -1;
    }

    if (ida != inactive)
        return -1;
    else
        return 1;
}

struct vshDomainList {
    virDomainPtr *domains;
    size_t ndomains;
};
typedef struct vshDomainList *vshDomainListPtr;

static void
vshDomainListFree(vshDomainListPtr domlist)
{
    int i;

    if (domlist && domlist->domains) {
        for (i = 0; i < domlist->ndomains; i++) {
            if (domlist->domains[i])
                virDomainFree(domlist->domains[i]);
        }
        VIR_FREE(domlist->domains);
    }
    VIR_FREE(domlist);
}

#define MATCH(FLAG) (flags & (FLAG))
static vshDomainListPtr
vshDomainListCollect(vshControl *ctl, unsigned int flags)
{
    vshDomainListPtr list = vshMalloc(ctl, sizeof(*list));
    int i;
    int ret;
    int *ids = NULL;
    int nids = 0;
    char **names = NULL;
    int nnames = 0;
    virDomainPtr dom;
    bool success = false;
    size_t deleted = 0;
    int persistent;
    int autostart;
    int state;
    int nsnap;
    int mansave;

    /* try the list with flags support (0.9.13 and later) */
    if ((ret = virConnectListAllDomains(ctl->conn, &list->domains,
                                        flags)) >= 0) {
        list->ndomains = ret;
        goto finished;
    }

    /* check if the command is actually supported */
    if (last_error && last_error->code == VIR_ERR_NO_SUPPORT) {
        virFreeError(last_error);
        last_error = NULL;
        goto fallback;
    }

    if (last_error && last_error->code ==  VIR_ERR_INVALID_ARG) {
        /* try the new API again but mask non-guaranteed flags */
        unsigned int newflags = flags & (VIR_CONNECT_LIST_DOMAINS_ACTIVE |
                                         VIR_CONNECT_LIST_DOMAINS_INACTIVE);

        virFreeError(last_error);
        last_error = NULL;
        if ((ret = virConnectListAllDomains(ctl->conn, &list->domains,
                                            newflags)) >= 0) {
            list->ndomains = ret;
            goto filter;
        }
    }

    /* there was an error during the first or second call */
    vshError(ctl, "%s", _("Failed to list domains"));
    goto cleanup;


fallback:
    /* fall back to old method (0.9.12 and older) */
    virResetLastError();

    /* list active domains, if necessary */
    if (!MATCH(VIR_CONNECT_LIST_FILTERS_ACTIVE) ||
        MATCH(VIR_CONNECT_LIST_DOMAINS_ACTIVE)) {
        if ((nids = virConnectNumOfDomains(ctl->conn)) < 0) {
            vshError(ctl, "%s", _("Failed to list active domains"));
            goto cleanup;
        }

        if (nids) {
            ids = vshMalloc(ctl, sizeof(int) * nids);

            if ((nids = virConnectListDomains(ctl->conn, ids, nids)) < 0) {
                vshError(ctl, "%s", _("Failed to list active domains"));
                goto cleanup;
            }
        }
    }

    if (!MATCH(VIR_CONNECT_LIST_FILTERS_ACTIVE) ||
        MATCH(VIR_CONNECT_LIST_DOMAINS_INACTIVE)) {
        if ((nnames = virConnectNumOfDefinedDomains(ctl->conn)) < 0) {
            vshError(ctl, "%s", _("Failed to list inactive domains"));
            goto cleanup;
        }

        if (nnames) {
            names = vshMalloc(ctl, sizeof(char *) * nnames);

            if ((nnames = virConnectListDefinedDomains(ctl->conn, names,
                                                      nnames)) < 0) {
                vshError(ctl, "%s", _("Failed to list inactive domains"));
                goto cleanup;
            }
        }
    }

    list->domains = vshMalloc(ctl, sizeof(virDomainPtr) * (nids + nnames));
    list->ndomains = 0;

    /* get active domains */
    for (i = 0; i < nids; i++) {
        if (!(dom = virDomainLookupByID(ctl->conn, ids[i])))
            continue;
        list->domains[list->ndomains++] = dom;
    }

    /* get inactive domains */
    for (i = 0; i < nnames; i++) {
        if (!(dom = virDomainLookupByName(ctl->conn, names[i])))
            continue;
        list->domains[list->ndomains++] = dom;
    }

    /* truncate domains that weren't found */
    deleted = (nids + nnames) - list->ndomains;

filter:
    /* filter list the list if the list was acquired by fallback means */
    for (i = 0; i < list->ndomains; i++) {
        dom = list->domains[i];

        /* persistence filter */
        if (MATCH(VIR_CONNECT_LIST_FILTERS_PERSISTENT)) {
            if ((persistent = virDomainIsPersistent(dom)) < 0) {
                vshError(ctl, "%s", _("Failed to get domain persistence info"));
                goto cleanup;
            }

            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_PERSISTENT) && persistent) ||
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_TRANSIENT) && !persistent)))
                goto remove_entry;
        }

        /* domain state filter */
        if (MATCH(VIR_CONNECT_LIST_FILTERS_STATE)) {
            if (virDomainGetState(dom, &state, NULL, 0) < 0) {
                vshError(ctl, "%s", _("Failed to get domain state"));
                goto cleanup;
            }

            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_RUNNING) &&
                   state == VIR_DOMAIN_RUNNING) ||
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_PAUSED) &&
                   state == VIR_DOMAIN_PAUSED) ||
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_SHUTOFF) &&
                   state == VIR_DOMAIN_SHUTOFF) ||
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_OTHER) &&
                   (state != VIR_DOMAIN_RUNNING &&
                    state != VIR_DOMAIN_PAUSED &&
                    state != VIR_DOMAIN_SHUTOFF))))
                goto remove_entry;
        }

        /* autostart filter */
        if (MATCH(VIR_CONNECT_LIST_FILTERS_AUTOSTART)) {
            if (virDomainGetAutostart(dom, &autostart) < 0) {
                vshError(ctl, "%s", _("Failed to get domain autostart state"));
                goto cleanup;
            }

            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_AUTOSTART) && autostart) ||
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_AUTOSTART) && !autostart)))
                goto remove_entry;
        }

        /* managed save filter */
        if (MATCH(VIR_CONNECT_LIST_FILTERS_MANAGEDSAVE)) {
            if ((mansave = virDomainHasManagedSaveImage(dom, 0)) < 0) {
                vshError(ctl, "%s",
                         _("Failed to check for managed save image"));
                goto cleanup;
            }

            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_MANAGEDSAVE) && mansave) ||
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_MANAGEDSAVE) && !mansave)))
                goto remove_entry;
        }

        /* snapshot filter */
        if (MATCH(VIR_CONNECT_LIST_FILTERS_SNAPSHOT)) {
            if ((nsnap = virDomainSnapshotNum(dom, 0)) < 0) {
                vshError(ctl, "%s", _("Failed to get snapshot count"));
                goto cleanup;
            }
            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT) && nsnap > 0) ||
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT) && nsnap == 0)))
                goto remove_entry;
        }

        /* the domain matched all filters, it may stay */
        continue;

remove_entry:
        /* the domain has to be removed as it failed one of the filters */
        virDomainFree(list->domains[i]);
        list->domains[i] = NULL;
        deleted++;
    }

finished:
    /* sort the list */
    if (list->domains && list->ndomains)
        qsort(list->domains, list->ndomains, sizeof(*list->domains),
              vshDomainSorter);

    /* truncate the list if filter simulation deleted entries */
    if (deleted)
        VIR_SHRINK_N(list->domains, list->ndomains, deleted);

    success = true;

cleanup:
    for (i = 0; i < nnames; i++)
        VIR_FREE(names[i]);

    if (!success) {
        vshDomainListFree(list);
        list = NULL;
    }

    VIR_FREE(names);
    VIR_FREE(ids);
    return list;
}
#undef MATCH


1269
static const vshCmdOptDef opts_list[] = {
1270 1271
    {"inactive", VSH_OT_BOOL, 0, N_("list inactive domains")},
    {"all", VSH_OT_BOOL, 0, N_("list inactive & active domains")},
1272 1273
    {"transient", VSH_OT_BOOL, 0, N_("list transient domains")},
    {"persistent", VSH_OT_BOOL, 0, N_("list persistent domains")},
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
    {"with-snapshot", VSH_OT_BOOL, 0,
     N_("list domains with existing snapshot")},
    {"without-snapshot", VSH_OT_BOOL, 0,
     N_("list domains without a snapshot")},
    {"state-running", VSH_OT_BOOL, 0, N_("list domains in running state")},
    {"state-paused", VSH_OT_BOOL, 0, N_("list domains in paused state")},
    {"state-shutoff", VSH_OT_BOOL, 0, N_("list domains in shutoff state")},
    {"state-other", VSH_OT_BOOL, 0, N_("list domains in other states")},
    {"autostart", VSH_OT_BOOL, 0, N_("list domains with autostart enabled")},
    {"no-autostart", VSH_OT_BOOL, 0,
     N_("list domains with autostart disabled")},
    {"with-managed-save", VSH_OT_BOOL, 0,
     N_("list domains with managed save state")},
    {"without-managed-save", VSH_OT_BOOL, 0,
     N_("list domains without managed save")},
1289 1290 1291
    {"uuid", VSH_OT_BOOL, 0, N_("list uuid's only")},
    {"name", VSH_OT_BOOL, 0, N_("list domain names only")},
    {"table", VSH_OT_BOOL, 0, N_("list table (default)")},
E
Eric Blake 已提交
1292
    {"managed-save", VSH_OT_BOOL, 0,
1293
     N_("mark inactive domains with managed save state")},
1294
    {"title", VSH_OT_BOOL, 0, N_("show short domain description")},
1295 1296 1297
    {NULL, 0, 0, NULL}
};

K
Karel Zak 已提交
1298

1299 1300 1301
#define FILTER(NAME, FLAG)              \
    if (vshCommandOptBool(cmd, NAME))   \
        flags |= (FLAG)
E
Eric Blake 已提交
1302
static bool
1303
cmdList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
1304
{
E
Eric Blake 已提交
1305
    bool managed = vshCommandOptBool(cmd, "managed-save");
1306 1307 1308 1309
    bool optTitle = vshCommandOptBool(cmd, "title");
    bool optTable = vshCommandOptBool(cmd, "table");
    bool optUUID = vshCommandOptBool(cmd, "uuid");
    bool optName = vshCommandOptBool(cmd, "name");
1310
    int i;
1311
    char *title;
1312
    char uuid[VIR_UUID_STRING_BUFLEN];
E
Eric Blake 已提交
1313
    int state;
1314
    bool ret = false;
1315 1316 1317 1318 1319
    vshDomainListPtr list = NULL;
    virDomainPtr dom;
    char id_buf[INT_BUFSIZE_BOUND(unsigned int)];
    unsigned int id;
    unsigned int flags = VIR_CONNECT_LIST_DOMAINS_ACTIVE;
E
Eric Blake 已提交
1320

1321 1322 1323
    /* construct filter flags */
    if (vshCommandOptBool(cmd, "inactive"))
        flags = VIR_CONNECT_LIST_DOMAINS_INACTIVE;
K
Karel Zak 已提交
1324

1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
    if (vshCommandOptBool(cmd, "all"))
        flags = VIR_CONNECT_LIST_DOMAINS_INACTIVE |
                VIR_CONNECT_LIST_DOMAINS_ACTIVE;

    FILTER("persistent", VIR_CONNECT_LIST_DOMAINS_PERSISTENT);
    FILTER("transient",  VIR_CONNECT_LIST_DOMAINS_TRANSIENT);

    FILTER("with-managed-save",    VIR_CONNECT_LIST_DOMAINS_MANAGEDSAVE);
    FILTER("without-managed-save", VIR_CONNECT_LIST_DOMAINS_NO_MANAGEDSAVE);

    FILTER("autostart",    VIR_CONNECT_LIST_DOMAINS_AUTOSTART);
    FILTER("no-autostart", VIR_CONNECT_LIST_DOMAINS_NO_AUTOSTART);

    FILTER("with-snapshot",    VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT);
    FILTER("without-snapshot", VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT);

    FILTER("state-running", VIR_CONNECT_LIST_DOMAINS_RUNNING);
    FILTER("state-paused",  VIR_CONNECT_LIST_DOMAINS_PAUSED);
    FILTER("state-shutoff", VIR_CONNECT_LIST_DOMAINS_SHUTOFF);
    FILTER("state-other",   VIR_CONNECT_LIST_DOMAINS_OTHER);
1345 1346 1347

    if (optTable + optName + optUUID > 1) {
        vshError(ctl, "%s",
1348
                 _("Only one argument from --table, --name and --uuid "
1349 1350 1351 1352 1353 1354 1355
                   "may be specified."));
        return false;
    }

    if (!optUUID && !optName)
        optTable = true;

1356
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
1357
        return false;
1358

1359 1360
    if (!(list = vshDomainListCollect(ctl, flags)))
        goto cleanup;
1361

1362 1363
    /* print table header in legacy mode */
    if (optTable) {
1364
        if (optTitle)
1365 1366 1367 1368
            vshPrintExtra(ctl, " %-5s %-30s %-10s %-20s\n%s\n",
                          _("Id"), _("Name"), _("State"), _("Title"),
                          "-----------------------------------------"
                          "-----------------------------------------");
1369
        else
1370 1371 1372 1373
            vshPrintExtra(ctl, " %-5s %-30s %s\n%s\n",
                          _("Id"), _("Name"), _("State"),
                          "-----------------------------------------"
                          "-----------");
1374
    }
1375

1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
    for (i = 0; i < list->ndomains; i++) {
        dom = list->domains[i];
        id = virDomainGetID(dom);
        if (id != (unsigned int) -1)
            snprintf(id_buf, sizeof(id_buf), "%d", id);
        else
            ignore_value(virStrcpyStatic(id_buf, "-"));

        state = vshDomainState(ctl, dom, NULL);
        if (optTable && managed && state == VIR_DOMAIN_SHUTOFF &&
            virDomainHasManagedSaveImage(dom, 0) > 0)
            state = -2;

        if (optTable) {
            if (optTitle) {
                if (!(title = vshGetDomainDescription(ctl, dom, true, 0)))
                    goto cleanup;

                vshPrint(ctl, " %-5s %-30s %-10s %-20s\n", id_buf,
                         virDomainGetName(dom),
                         state == -2 ? _("saved") : _(vshDomainStateToString(state)),
                         title);

                VIR_FREE(title);
            } else {
                vshPrint(ctl, " %-5s %-30s %s\n", id_buf,
                         virDomainGetName(dom),
                         state == -2 ? _("saved") : _(vshDomainStateToString(state)));
1404
            }
1405 1406 1407 1408
        } else if (optUUID) {
            if (virDomainGetUUIDString(dom, uuid) < 0) {
                vshError(ctl, "%s", _("Failed to get domain's UUID"));
                goto cleanup;
1409
            }
1410 1411 1412
            vshPrint(ctl, "%s\n", uuid);
        } else if (optName) {
            vshPrint(ctl, "%s\n", virDomainGetName(dom));
1413
        }
1414
    }
1415 1416 1417

    ret = true;
cleanup:
1418
    vshDomainListFree(list);
1419 1420
    return ret;
}
1421
#undef FILTER
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436

/*
 * "desc" command for managing domain description and title
 */
static const vshCmdInfo info_desc[] = {
    {"help", N_("show or set domain's description or title")},
    {"desc", N_("Allows to show or modify description or title of a domain.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_desc[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"live", VSH_OT_BOOL, 0, N_("modify/get running state")},
    {"config", VSH_OT_BOOL, 0, N_("modify/get persistent configuration")},
    {"current", VSH_OT_BOOL, 0, N_("modify/get current state configuration")},
1437
    {"title", VSH_OT_BOOL, 0, N_("modify/get the title instead of description")},
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
    {"edit", VSH_OT_BOOL, 0, N_("open an editor to modify the description")},
    {"new-desc", VSH_OT_ARGV, 0, N_("message")},
    {NULL, 0, 0, NULL}
};

static bool
cmdDesc(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    virDomainPtr dom;
    bool config = vshCommandOptBool(cmd, "config");
    bool live = vshCommandOptBool(cmd, "live");
1449
    bool current = vshCommandOptBool(cmd, "current");
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465

    bool title = vshCommandOptBool(cmd, "title");
    bool edit = vshCommandOptBool(cmd, "edit");

    int state;
    int type;
    char *desc = NULL;
    char *desc_edited = NULL;
    char *tmp = NULL;
    char *tmpstr;
    const vshCmdOpt *opt = NULL;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    bool pad = false;
    bool ret = false;
    unsigned int flags = VIR_DOMAIN_AFFECT_CURRENT;

1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
    if (current) {
        if (live || config) {
            vshError(ctl, "%s", _("--current must be specified exclusively"));
            return false;
        }
        flags = VIR_DOMAIN_AFFECT_CURRENT;
    } else {
        if (config)
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
        if (live)
            flags |= VIR_DOMAIN_AFFECT_LIVE;
    }

1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
    if (!vshConnectionUsability(ctl, ctl->conn))
        return false;

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
        return false;

    if ((state = vshDomainState(ctl, dom, NULL)) < 0)
        goto cleanup;

    while ((opt = vshCommandOptArgv(cmd, opt))) {
        if (pad)
            virBufferAddChar(&buf, ' ');
        pad = true;
        virBufferAdd(&buf, opt->data, -1);
    }

    if (title)
        type = VIR_DOMAIN_METADATA_TITLE;
    else
        type = VIR_DOMAIN_METADATA_DESCRIPTION;

    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to collect new description/title"));
        goto cleanup;
    }
    desc = virBufferContentAndReset(&buf);

    if (edit || desc) {
        if (!desc) {
                desc = vshGetDomainDescription(ctl, dom, title,
                                           config?VIR_DOMAIN_XML_INACTIVE:0);
                if (!desc)
                    goto cleanup;
        }

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

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

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

            /* strip a possible newline at the end of file; some
             * editors enforce a newline, this makes editing the title
1529
             * more convenient */
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
            if (title &&
                (tmpstr = strrchr(desc_edited, '\n')) &&
                *(tmpstr+1) == '\0')
                *tmpstr = '\0';

            /* Compare original XML with edited.  Has it changed at all? */
            if (STREQ(desc, desc_edited)) {
                vshPrint(ctl, _("Domain description not changed.\n"));
                ret = true;
                goto cleanup;
            }

            VIR_FREE(desc);
            desc = desc_edited;
            desc_edited = NULL;
        }

        if (virDomainSetMetadata(dom, type, desc, NULL, NULL, flags) < 0) {
            vshError(ctl, "%s",
                     _("Failed to set new domain description"));
            goto cleanup;
        }
        vshPrint(ctl, "%s", _("Domain description updated successfully"));
    } else {
        desc = vshGetDomainDescription(ctl, dom, title,
                                       config?VIR_DOMAIN_XML_INACTIVE:0);
        if (!desc)
            goto cleanup;

        if (strlen(desc) > 0)
            vshPrint(ctl, "%s", desc);
        else
            vshPrint(ctl, _("No description for domain: %s"),
                     virDomainGetName(dom));
    }

    ret = true;
cleanup:
    VIR_FREE(desc_edited);
    VIR_FREE(desc);
    if (tmp) {
        unlink(tmp);
        VIR_FREE(tmp);
    }
A
Alex Jia 已提交
1574 1575
    if (dom)
        virDomainFree(dom);
1576
    return ret;
K
Karel Zak 已提交
1577 1578 1579
}

/*
K
Karel Zak 已提交
1580
 * "domstate" command
K
Karel Zak 已提交
1581
 */
1582
static const vshCmdInfo info_domstate[] = {
1583 1584
    {"help", N_("domain state")},
    {"desc", N_("Returns state about a domain.")},
1585
    {NULL, NULL}
K
Karel Zak 已提交
1586 1587
};

1588
static const vshCmdOptDef opts_domstate[] = {
1589
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
1590
    {"reason", VSH_OT_BOOL, 0, N_("also print reason for the state")},
1591
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
1592 1593
};

E
Eric Blake 已提交
1594
static bool
1595
cmdDomstate(vshControl *ctl, const vshCmd *cmd)
1596
{
K
Karel Zak 已提交
1597
    virDomainPtr dom;
E
Eric Blake 已提交
1598
    bool ret = true;
1599
    bool showReason = vshCommandOptBool(cmd, "reason");
1600
    int state, reason;
1601

1602
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
1603
        return false;
1604

J
Jim Meyering 已提交
1605
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
1606
        return false;
1607

1608
    if ((state = vshDomainState(ctl, dom, &reason)) < 0) {
E
Eric Blake 已提交
1609
        ret = false;
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
        goto cleanup;
    }

    if (showReason) {
        vshPrint(ctl, "%s (%s)\n",
                 _(vshDomainStateToString(state)),
                 vshDomainStateReasonToString(state, reason));
    } else {
        vshPrint(ctl, "%s\n",
                 _(vshDomainStateToString(state)));
    }
1621

1622
cleanup:
1623 1624 1625 1626
    virDomainFree(dom);
    return ret;
}

1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
/*
 * "domcontrol" command
 */
static const vshCmdInfo info_domcontrol[] = {
    {"help", N_("domain control interface state")},
    {"desc", N_("Returns state of a control interface to the domain.")},
    {NULL, NULL}
};

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

static bool
cmdDomControl(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    bool ret = true;
    virDomainControlInfo info;

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

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
        return false;

    if (virDomainGetControlInfo(dom, &info, 0) < 0) {
        ret = false;
        goto cleanup;
    }

    if (info.state != VIR_DOMAIN_CONTROL_OK &&
        info.state != VIR_DOMAIN_CONTROL_ERROR) {
        vshPrint(ctl, "%s (%0.3fs)\n",
                 _(vshDomainControlStateToString(info.state)),
                 info.stateTime / 1000.0);
    } else {
        vshPrint(ctl, "%s\n",
                 _(vshDomainControlStateToString(info.state)));
    }

cleanup:
    virDomainFree(dom);
    return ret;
}

1674 1675
/* "domblkstat" command
 */
1676
static const vshCmdInfo info_domblkstat[] = {
1677
    {"help", N_("get device block stats for a domain")},
1678 1679
    {"desc", N_("Get device block stats for a running domain. See man page or "
                "use --human for explanation of fields")},
1680 1681 1682
    {NULL,NULL}
};

1683
static const vshCmdOptDef opts_domblkstat[] = {
1684 1685
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("block device")},
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
    {"human",  VSH_OT_BOOL, 0, N_("print a more human readable output")},
    {NULL, 0, 0, NULL}
};

struct _domblkstat_sequence {
    const char *field;  /* field name */
    const char *legacy; /* legacy name from previous releases */
    const char *human;  /* human-friendly explanation */
};

/* sequence of values for output to honor legacy format from previous
 * versions */
static const struct _domblkstat_sequence domblkstat_output[] = {
    { VIR_DOMAIN_BLOCK_STATS_READ_REQ,          "rd_req",
1700
      N_("number of read operations:") }, /* 0 */
1701
    { VIR_DOMAIN_BLOCK_STATS_READ_BYTES,        "rd_bytes",
1702
      N_("number of bytes read:") }, /* 1 */
1703
    { VIR_DOMAIN_BLOCK_STATS_WRITE_REQ,         "wr_req",
1704
      N_("number of write operations:") }, /* 2 */
1705
    { VIR_DOMAIN_BLOCK_STATS_WRITE_BYTES,       "wr_bytes",
1706
      N_("number of bytes written:") }, /* 3 */
1707
    { VIR_DOMAIN_BLOCK_STATS_ERRS,              "errs",
1708
      N_("error count:") }, /* 4 */
1709
    { VIR_DOMAIN_BLOCK_STATS_FLUSH_REQ,         NULL,
1710
      N_("number of flush operations:") }, /* 5 */
1711
    { VIR_DOMAIN_BLOCK_STATS_READ_TOTAL_TIMES,  NULL,
1712
      N_("total duration of reads (ns):") }, /* 6 */
1713
    { VIR_DOMAIN_BLOCK_STATS_WRITE_TOTAL_TIMES, NULL,
1714
      N_("total duration of writes (ns):") }, /* 7 */
1715 1716 1717 1718 1719 1720 1721
    { VIR_DOMAIN_BLOCK_STATS_FLUSH_TOTAL_TIMES, NULL,
      N_("total duration of flushes (ns):") }, /* 8 */
    { NULL, NULL, NULL }
};

#define DOMBLKSTAT_LEGACY_PRINT(ID, VALUE)              \
    if (VALUE >= 0)                                     \
1722 1723
        vshPrint(ctl, "%s %-*s %lld\n", device,         \
                 human ? 31 : 0,                        \
1724 1725 1726
                 human ? _(domblkstat_output[ID].human) \
                 : domblkstat_output[ID].legacy,        \
                 VALUE);
1727

E
Eric Blake 已提交
1728
static bool
1729
cmdDomblkstat (vshControl *ctl, const vshCmd *cmd)
1730 1731
{
    virDomainPtr dom;
1732
    const char *name = NULL, *device = NULL;
1733
    struct _virDomainBlockStats stats;
1734
    virTypedParameterPtr params = NULL;
1735 1736 1737
    virTypedParameterPtr par = NULL;
    char *value = NULL;
    const char *field = NULL;
1738
    int rc, nparams = 0;
1739
    int i = 0;
1740
    bool ret = false;
1741
    bool human = vshCommandOptBool(cmd, "human"); /* human readable output */
1742

1743
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
1744
        return false;
1745

1746
    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
E
Eric Blake 已提交
1747
        return false;
1748

1749
    if (vshCommandOptString(cmd, "device", &device) <= 0)
1750
        goto cleanup;
1751

1752 1753 1754 1755 1756 1757 1758
    rc = virDomainBlockStatsFlags(dom, device, NULL, &nparams, 0);

    /* It might fail when virDomainBlockStatsFlags is not
     * supported on older libvirt, fallback to use virDomainBlockStats
     * then.
     */
    if (rc < 0) {
1759 1760
        /* try older API if newer is not supported */
        if (last_error->code != VIR_ERR_NO_SUPPORT)
1761 1762
            goto cleanup;

1763 1764
        virFreeError(last_error);
        last_error = NULL;
1765

1766
        if (virDomainBlockStats(dom, device, &stats,
1767
                                sizeof(stats)) == -1) {
1768 1769 1770 1771
            vshError(ctl, _("Failed to get block stats %s %s"),
                     name, device);
            goto cleanup;
        }
1772

1773 1774 1775 1776
        /* human friendly output */
        if (human) {
            vshPrint(ctl, N_("Device: %s\n"), device);
            device = "";
1777
        }
1778 1779 1780 1781 1782 1783

        DOMBLKSTAT_LEGACY_PRINT(0, stats.rd_req);
        DOMBLKSTAT_LEGACY_PRINT(1, stats.rd_bytes);
        DOMBLKSTAT_LEGACY_PRINT(2, stats.wr_req);
        DOMBLKSTAT_LEGACY_PRINT(3, stats.wr_bytes);
        DOMBLKSTAT_LEGACY_PRINT(4, stats.errs);
1784
    } else {
1785
        params = vshCalloc(ctl, nparams, sizeof(*params));
1786

1787 1788 1789 1790
        if (virDomainBlockStatsFlags (dom, device, params, &nparams, 0) < 0) {
            vshError(ctl, _("Failed to get block stats %s %s"), name, device);
            goto cleanup;
        }
1791

1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804
        /* set for prettier output */
        if (human) {
            vshPrint(ctl, N_("Device: %s\n"), device);
            device = "";
        }

        /* at first print all known values in desired order */
        for (i = 0; domblkstat_output[i].field != NULL; i++) {
            if (!(par = vshFindTypedParamByName(domblkstat_output[i].field,
                                                params,
                                                nparams)))
                continue;

1805
            value = vshGetTypedParamValue(ctl, par);
1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820

            /* to print other not supported fields, mark the already printed */
            par->field[0] = '\0'; /* set the name to empty string */

            /* translate into human readable or legacy spelling */
            field = NULL;
            if (human)
                field = _(domblkstat_output[i].human);
            else
                field = domblkstat_output[i].legacy;

            /* use the provided spelling if no translation is available */
            if (!field)
                field = domblkstat_output[i].field;

1821 1822
            vshPrint(ctl, "%s %-*s %s\n", device,
                     human ? 31 : 0, field, value);
1823 1824 1825 1826 1827

            VIR_FREE(value);
        }

        /* go through the fields again, for remaining fields */
1828
        for (i = 0; i < nparams; i++) {
1829 1830
            if (!*params[i].field)
                continue;
1831

1832
            value = vshGetTypedParamValue(ctl, params+i);
1833 1834
            vshPrint(ctl, "%s %s %s\n", device, params[i].field, value);
            VIR_FREE(value);
1835 1836 1837 1838 1839 1840 1841
        }
    }

    ret = true;

cleanup:
    VIR_FREE(params);
1842
    virDomainFree(dom);
1843
    return ret;
1844
}
1845
#undef DOMBLKSTAT_LEGACY_PRINT
1846 1847 1848

/* "domifstat" command
 */
1849
static const vshCmdInfo info_domifstat[] = {
1850 1851
    {"help", N_("get network interface stats for a domain")},
    {"desc", N_("Get network interface stats for a running domain.")},
1852 1853 1854
    {NULL,NULL}
};

1855
static const vshCmdOptDef opts_domifstat[] = {
1856 1857
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface device")},
1858 1859 1860
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
1861
static bool
1862
cmdDomIfstat (vshControl *ctl, const vshCmd *cmd)
1863 1864
{
    virDomainPtr dom;
1865
    const char *name = NULL, *device = NULL;
1866 1867
    struct _virDomainInterfaceStats stats;

1868
    if (!vshConnectionUsability (ctl, ctl->conn))
E
Eric Blake 已提交
1869
        return false;
1870

J
Jim Meyering 已提交
1871
    if (!(dom = vshCommandOptDomain (ctl, cmd, &name)))
E
Eric Blake 已提交
1872
        return false;
1873

1874
    if (vshCommandOptString (cmd, "interface", &device) <= 0) {
L
Laine Stump 已提交
1875
        virDomainFree(dom);
E
Eric Blake 已提交
1876
        return false;
L
Laine Stump 已提交
1877
    }
1878

1879
    if (virDomainInterfaceStats (dom, device, &stats, sizeof(stats)) == -1) {
1880
        vshError(ctl, _("Failed to get interface stats %s %s"), name, device);
1881
        virDomainFree(dom);
E
Eric Blake 已提交
1882
        return false;
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
    }

    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);
E
Eric Blake 已提交
1910
    return true;
1911 1912
}

1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924
/* "domif-setlink" command
 */
static const vshCmdInfo info_domif_setlink[] = {
    {"help", N_("set link state of a virtual interface")},
    {"desc", N_("Set link state of a domain's virtual interface. This command wraps usage of update-device command.")},
    {NULL,NULL}
};

static const vshCmdOptDef opts_domif_setlink[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface device (MAC Address)")},
    {"state", VSH_OT_DATA, VSH_OFLAG_REQ, N_("new state of the device")},
1925 1926
    {"persistent", VSH_OT_ALIAS, 0, "config"},
    {"config", VSH_OT_BOOL, 0, N_("affect next boot")},
1927 1928 1929 1930 1931 1932 1933
    {NULL, 0, 0, NULL}
};

static bool
cmdDomIfSetLink (vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
1934
    const char *iface;
1935
    const char *state;
1936
    const char *value;
1937
    const char *desc;
1938 1939 1940
    unsigned char macaddr[VIR_MAC_BUFLEN];
    const char *element;
    const char *attr;
1941
    bool config;
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
    bool ret = false;
    unsigned int flags = 0;
    int i;
    xmlDocPtr xml = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlXPathObjectPtr obj = NULL;
    xmlNodePtr cur = NULL;
    xmlBufferPtr xml_buf = NULL;

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

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
        return false;

1957
    if (vshCommandOptString(cmd, "interface", &iface) <= 0)
1958 1959 1960 1961 1962
        goto cleanup;

    if (vshCommandOptString(cmd, "state", &state) <= 0)
        goto cleanup;

1963
    config = vshCommandOptBool(cmd, "config");
1964 1965 1966 1967 1968 1969 1970

    if (STRNEQ(state, "up") && STRNEQ(state, "down")) {
        vshError(ctl, _("invalid link state '%s'"), state);
        goto cleanup;
    }

    /* get persistent or live description of network device */
1971
    desc = virDomainGetXMLDesc(dom, config ? VIR_DOMAIN_XML_INACTIVE : 0);
1972 1973 1974 1975 1976
    if (desc == NULL) {
        vshError(ctl, _("Failed to get domain description xml"));
        goto cleanup;
    }

1977
    if (config)
1978 1979 1980 1981 1982 1983 1984 1985
        flags = VIR_DOMAIN_AFFECT_CONFIG;
    else
        flags = VIR_DOMAIN_AFFECT_LIVE;

    if (virDomainIsActive(dom) == 0)
        flags = VIR_DOMAIN_AFFECT_CONFIG;

    /* extract current network device description */
1986
    xml = virXMLParseStringCtxt(desc, _("(domain_definition)"), &ctxt);
1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
    VIR_FREE(desc);
    if (!xml) {
        vshError(ctl, _("Failed to parse domain description xml"));
        goto cleanup;
    }

    obj = xmlXPathEval(BAD_CAST "/domain/devices/interface", ctxt);
    if (obj == NULL || obj->type != XPATH_NODESET ||
        obj->nodesetval == NULL || obj->nodesetval->nodeNr == 0) {
        vshError(ctl, _("Failed to extract interface information or no interfaces found"));
        goto cleanup;
    }

2000
    if (virMacAddrParse(iface, macaddr) == 0) {
2001 2002 2003 2004 2005 2006 2007
        element = "mac";
        attr = "address";
    } else {
        element = "target";
        attr = "dev";
    }

2008 2009 2010 2011 2012 2013
    /* find interface with matching mac addr */
    for (i = 0; i < obj->nodesetval->nodeNr; i++) {
        cur = obj->nodesetval->nodeTab[i]->children;

        while (cur) {
            if (cur->type == XML_ELEMENT_NODE &&
2014 2015
                xmlStrEqual(cur->name, BAD_CAST element)) {
                value = virXMLPropString(cur, attr);
2016

2017 2018
                if (STRCASEEQ(value, iface)) {
                    VIR_FREE(value);
2019 2020
                    goto hit;
                }
2021
                VIR_FREE(value);
2022 2023 2024 2025 2026
            }
            cur = cur->next;
        }
    }

2027
    vshError(ctl, _("interface (%s: %s) not found"), element, iface);
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100
    goto cleanup;

hit:
    /* find and modify/add link state node */
    /* try to find <link> element */
    cur = obj->nodesetval->nodeTab[i]->children;

    while (cur) {
        if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "link")) {
            /* found, just modify the property */
            xmlSetProp(cur, BAD_CAST "state", BAD_CAST state);

            break;
        }
        cur = cur->next;
    }

    if (!cur) {
        /* element <link> not found, add one */
        cur = xmlNewChild(obj->nodesetval->nodeTab[i],
                          NULL,
                          BAD_CAST "link",
                          NULL);
        if (!cur)
            goto cleanup;

        if (xmlNewProp(cur, BAD_CAST "state", BAD_CAST state) == NULL)
            goto cleanup;
    }

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

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

    if (virDomainUpdateDeviceFlags(dom, (char *)xmlBufferContent(xml_buf), flags) < 0) {
        vshError(ctl, _("Failed to update interface link state"));
        goto cleanup;
    } else {
        vshPrint(ctl, "%s", _("Device updated successfully\n"));
        ret = true;
    }

cleanup:
    xmlXPathFreeObject(obj);
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml);
    xmlBufferFree(xml_buf);

    if (dom)
        virDomainFree(dom);

    return ret;
}

/* "domif-getlink" command
 */
static const vshCmdInfo info_domif_getlink[] = {
    {"help", N_("get link state of a virtual interface")},
    {"desc", N_("Get link state of a domain's virtual interface.")},
    {NULL,NULL}
};

static const vshCmdOptDef opts_domif_getlink[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface device (MAC Address)")},
2101 2102
    {"persistent", VSH_OT_ALIAS, 0, "config"},
    {"config", VSH_OT_BOOL, 0, N_("Get persistent interface state")},
2103 2104 2105 2106 2107 2108 2109
    {NULL, 0, 0, NULL}
};

static bool
cmdDomIfGetLink (vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
2110
    const char *iface = NULL;
2111 2112
    int flags = 0;
    char *state = NULL;
2113 2114 2115 2116
    char *value = NULL;
    unsigned char macaddr[VIR_MAC_BUFLEN];
    const char *element;
    const char *attr;
2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130
    bool ret = false;
    int i;
    char *desc;
    xmlDocPtr xml = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlNodePtr cur = NULL;
    xmlXPathObjectPtr obj = NULL;

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

    if (!(dom = vshCommandOptDomain (ctl, cmd, NULL)))
        return false;

2131
    if (vshCommandOptString (cmd, "interface", &iface) <= 0) {
2132 2133 2134 2135
        virDomainFree(dom);
        return false;
    }

2136
    if (vshCommandOptBool(cmd, "config"))
2137 2138 2139 2140 2141 2142 2143 2144
        flags = VIR_DOMAIN_XML_INACTIVE;

    desc = virDomainGetXMLDesc(dom, flags);
    if (desc == NULL) {
        vshError(ctl, _("Failed to get domain description xml"));
        goto cleanup;
    }

2145
    xml = virXMLParseStringCtxt(desc, _("(domain_definition)"), &ctxt);
2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
    VIR_FREE(desc);
    if (!xml) {
        vshError(ctl, _("Failed to parse domain description xml"));
        goto cleanup;
    }

    obj = xmlXPathEval(BAD_CAST "/domain/devices/interface", ctxt);
    if (obj == NULL || obj->type != XPATH_NODESET ||
        obj->nodesetval == NULL || obj->nodesetval->nodeNr == 0) {
        vshError(ctl, _("Failed to extract interface information or no interfaces found"));
        goto cleanup;
    }

2159
    if (virMacAddrParse(iface, macaddr) == 0) {
2160 2161 2162 2163 2164 2165 2166
        element = "mac";
        attr = "address";
    } else {
        element = "target";
        attr = "dev";
    }

2167 2168 2169 2170 2171 2172
    /* find interface with matching mac addr */
    for (i = 0; i < obj->nodesetval->nodeNr; i++) {
        cur = obj->nodesetval->nodeTab[i]->children;

        while (cur) {
            if (cur->type == XML_ELEMENT_NODE &&
2173
                xmlStrEqual(cur->name, BAD_CAST element)) {
2174

2175
                value = virXMLPropString(cur, attr);
2176

2177 2178
                if (STRCASEEQ(value, iface)) {
                    VIR_FREE(value);
2179 2180
                    goto hit;
                }
2181
                VIR_FREE(value);
2182 2183 2184 2185 2186
            }
            cur = cur->next;
        }
    }

2187
    vshError(ctl, _("Interface (%s: %s) not found."), element, iface);
2188 2189 2190 2191 2192 2193 2194 2195 2196
    goto cleanup;

hit:
    cur = obj->nodesetval->nodeTab[i]->children;
    while (cur) {
        if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "link")) {

            state = virXMLPropString(cur, "state");
2197
            vshPrint(ctl, "%s %s", iface, state);
2198 2199 2200 2201 2202 2203 2204 2205
            VIR_FREE(state);

            goto cleanup;
        }
        cur = cur->next;
    }

    /* attribute not found */
2206
    vshPrint(ctl, "%s default", iface);
2207

2208
    ret = true;
2209 2210 2211 2212 2213 2214 2215 2216 2217 2218
cleanup:
    xmlXPathFreeObject(obj);
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml);
    if (dom)
        virDomainFree(dom);

    return ret;
}

2219 2220 2221 2222 2223 2224 2225 2226 2227 2228
/* "domiftune" command
 */
static const vshCmdInfo info_domiftune[] = {
    {"help", N_("get/set parameters of a virtual interface")},
    {"desc", N_("Get/set parameters of a domain's virtual interface.")},
    {NULL,NULL}
};

static const vshCmdOptDef opts_domiftune[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
2229
    {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface device (MAC Address)")},
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247
    {"inbound", VSH_OT_DATA, VSH_OFLAG_NONE, N_("control domain's incoming traffics")},
    {"outbound", VSH_OT_DATA, VSH_OFLAG_NONE, N_("control domain's outgoing traffics")},
    {"config", VSH_OT_BOOL, VSH_OFLAG_NONE, N_("affect next boot")},
    {"live", VSH_OT_BOOL, VSH_OFLAG_NONE, N_("affect running domain")},
    {"current", VSH_OT_BOOL, VSH_OFLAG_NONE, N_("affect current domain")},
    {NULL, 0, 0, NULL}
};

static bool
cmdDomIftune(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    const char *name = NULL, *device = NULL,
               *inboundStr = NULL, *outboundStr = NULL;
    unsigned int flags = 0;
    int nparams = 0;
    virTypedParameterPtr params = NULL;
    bool ret = false;
2248 2249 2250
    bool current = vshCommandOptBool(cmd, "current");
    bool config = vshCommandOptBool(cmd, "config");
    bool live = vshCommandOptBool(cmd, "live");
2251 2252 2253 2254 2255 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 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413
    virNetDevBandwidthRate inbound, outbound;
    int i;

    if (current) {
        if (live || config) {
            vshError(ctl, "%s", _("--current must be specified exclusively"));
            return false;
        }
        flags = VIR_DOMAIN_AFFECT_CURRENT;
    } else {
        if (config)
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
        if (live)
            flags |= VIR_DOMAIN_AFFECT_LIVE;
    }

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

    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
        return false;

    if (vshCommandOptString(cmd, "interface", &device) <= 0) {
        virDomainFree(dom);
        return false;
    }

    if (vshCommandOptString(cmd, "inbound", &inboundStr) < 0 ||
        vshCommandOptString(cmd, "outbound", &outboundStr) < 0) {
        vshError(ctl, "missing argument");
        goto cleanup;
    }

    memset(&inbound, 0, sizeof(inbound));
    memset(&outbound, 0, sizeof(outbound));

    if (inboundStr) {
        if (parseRateStr(inboundStr, &inbound) < 0) {
            vshError(ctl, _("inbound format is incorrect"));
            goto cleanup;
        }
        if (inbound.average == 0) {
            vshError(ctl, _("inbound average is mandatory"));
            goto cleanup;
        }
        nparams++; /* average */
        if (inbound.peak) nparams++;
        if (inbound.burst) nparams++;
    }
    if (outboundStr) {
        if (parseRateStr(outboundStr, &outbound) < 0) {
            vshError(ctl, _("outbound format is incorrect"));
            goto cleanup;
        }
        if (outbound.average == 0) {
            vshError(ctl, _("outbound average is mandatory"));
            goto cleanup;
        }
        nparams++; /* average */
        if (outbound.peak) nparams++;
        if (outbound.burst) nparams++;
    }

    if (nparams == 0) {
        /* get the number of interface parameters */
        if (virDomainGetInterfaceParameters(dom, device, NULL, &nparams, flags) != 0) {
            vshError(ctl, "%s",
                     _("Unable to get number of interface parameters"));
            goto cleanup;
        }

        if (nparams == 0) {
            /* nothing to output */
            ret = true;
            goto cleanup;
        }

        /* get all interface parameters */
        params = vshCalloc(ctl, nparams, sizeof(*params));
        if (!params) {
            virReportOOMError();
            goto cleanup;
        }
        if (virDomainGetInterfaceParameters(dom, device, params, &nparams, flags) != 0) {
            vshError(ctl, "%s", _("Unable to get interface parameters"));
            goto cleanup;
        }

        for (i = 0; i < nparams; i++) {
            char *str = vshGetTypedParamValue(ctl, &params[i]);
            vshPrint(ctl, "%-15s: %s\n", params[i].field, str);
            VIR_FREE(str);
        }
    } else {
        /* set the interface parameters */
        params = vshCalloc(ctl, nparams, sizeof(*params));
        if (!params) {
            virReportOOMError();
            goto cleanup;
        }

        for (i = 0; i < nparams; i++)
            params[i].type = VIR_TYPED_PARAM_UINT;

        i = 0;
        if (inbound.average && i < nparams) {
            if (!virStrcpy(params[i].field, VIR_DOMAIN_BANDWIDTH_IN_AVERAGE,
                           sizeof(params[i].field)))
                goto cleanup;
            params[i].value.ui = inbound.average;
            i++;
        }
        if (inbound.peak && i < nparams) {
            if (!virStrcpy(params[i].field, VIR_DOMAIN_BANDWIDTH_IN_PEAK,
                           sizeof(params[i].field)))
                goto cleanup;
            params[i].value.ui = inbound.peak;
            i++;
        }
        if (inbound.burst && i < nparams) {
            if (!virStrcpy(params[i].field, VIR_DOMAIN_BANDWIDTH_IN_BURST,
                           sizeof(params[i].field)))
                goto cleanup;
            params[i].value.ui = inbound.burst;
            i++;
        }
        if (outbound.average && i < nparams) {
            if (!virStrcpy(params[i].field, VIR_DOMAIN_BANDWIDTH_OUT_AVERAGE,
                           sizeof(params[i].field)))
                goto cleanup;
            params[i].value.ui = outbound.average;
            i++;
        }
        if (outbound.peak && i < nparams) {
            if (!virStrcpy(params[i].field, VIR_DOMAIN_BANDWIDTH_OUT_PEAK,
                           sizeof(params[i].field)))
                goto cleanup;
            params[i].value.ui = outbound.peak;
            i++;
        }
        if (outbound.burst && i < nparams) {
            if (!virStrcpy(params[i].field, VIR_DOMAIN_BANDWIDTH_OUT_BURST,
                           sizeof(params[i].field)))
                goto cleanup;
            params[i].value.ui = outbound.burst;
            i++;
        }

        if (virDomainSetInterfaceParameters(dom, device, params, nparams, flags) != 0) {
            vshError(ctl, "%s", _("Unable to set interface parameters"));
            goto cleanup;
        }
    }

    ret = true;

cleanup:
    virTypedParameterArrayClear(params, nparams);
    VIR_FREE(params);
    virDomainFree(dom);
    return ret;
}

2414 2415 2416
/*
 * "dommemstats" command
 */
2417
static const vshCmdInfo info_dommemstat[] = {
2418
    {"help", N_("get memory statistics for a domain")},
Y
Yuri Chornoivan 已提交
2419
    {"desc", N_("Get memory statistics for a running domain.")},
2420 2421 2422
    {NULL,NULL}
};

2423
static const vshCmdOptDef opts_dommemstat[] = {
2424
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
2425 2426 2427
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
2428
static bool
2429
cmdDomMemStat(vshControl *ctl, const vshCmd *cmd)
2430 2431
{
    virDomainPtr dom;
2432
    const char *name;
2433 2434 2435
    struct _virDomainMemoryStat stats[VIR_DOMAIN_MEMORY_STAT_NR];
    unsigned int nr_stats, i;

2436
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
2437
        return false;
2438 2439

    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
E
Eric Blake 已提交
2440
        return false;
2441 2442 2443 2444 2445

    nr_stats = virDomainMemoryStats (dom, stats, VIR_DOMAIN_MEMORY_STAT_NR, 0);
    if (nr_stats == -1) {
        vshError(ctl, _("Failed to get memory statistics for domain %s"), name);
        virDomainFree(dom);
E
Eric Blake 已提交
2446
        return false;
2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461
    }

    for (i = 0; i < nr_stats; i++) {
        if (stats[i].tag == VIR_DOMAIN_MEMORY_STAT_SWAP_IN)
            vshPrint (ctl, "swap_in %llu\n", stats[i].val);
        if (stats[i].tag == VIR_DOMAIN_MEMORY_STAT_SWAP_OUT)
            vshPrint (ctl, "swap_out %llu\n", stats[i].val);
        if (stats[i].tag == VIR_DOMAIN_MEMORY_STAT_MAJOR_FAULT)
            vshPrint (ctl, "major_fault %llu\n", stats[i].val);
        if (stats[i].tag == VIR_DOMAIN_MEMORY_STAT_MINOR_FAULT)
            vshPrint (ctl, "minor_fault %llu\n", stats[i].val);
        if (stats[i].tag == VIR_DOMAIN_MEMORY_STAT_UNUSED)
            vshPrint (ctl, "unused %llu\n", stats[i].val);
        if (stats[i].tag == VIR_DOMAIN_MEMORY_STAT_AVAILABLE)
            vshPrint (ctl, "available %llu\n", stats[i].val);
2462 2463
        if (stats[i].tag == VIR_DOMAIN_MEMORY_STAT_ACTUAL_BALLOON)
            vshPrint (ctl, "actual %llu\n", stats[i].val);
M
Martin Kletzander 已提交
2464 2465
        if (stats[i].tag == VIR_DOMAIN_MEMORY_STAT_RSS)
            vshPrint (ctl, "rss %llu\n", stats[i].val);
2466 2467 2468
    }

    virDomainFree(dom);
E
Eric Blake 已提交
2469
    return true;
2470 2471
}

2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486
/*
 * "domblkinfo" command
 */
static const vshCmdInfo info_domblkinfo[] = {
    {"help", N_("domain block device size information")},
    {"desc", N_("Get block device size info for a domain.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_domblkinfo[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("block device")},
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
2487
static bool
2488 2489 2490 2491
cmdDomblkinfo(vshControl *ctl, const vshCmd *cmd)
{
    virDomainBlockInfo info;
    virDomainPtr dom;
E
Eric Blake 已提交
2492
    bool ret = true;
2493
    const char *device = NULL;
2494

2495
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
2496
        return false;
2497 2498

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
2499
        return false;
2500

2501
    if (vshCommandOptString (cmd, "device", &device) <= 0) {
2502
        virDomainFree(dom);
E
Eric Blake 已提交
2503
        return false;
2504 2505 2506 2507
    }

    if (virDomainGetBlockInfo(dom, device, &info, 0) < 0) {
        virDomainFree(dom);
E
Eric Blake 已提交
2508
        return false;
2509 2510 2511 2512 2513 2514 2515 2516 2517 2518
    }

    vshPrint(ctl, "%-15s %llu\n", _("Capacity:"), info.capacity);
    vshPrint(ctl, "%-15s %llu\n", _("Allocation:"), info.allocation);
    vshPrint(ctl, "%-15s %llu\n", _("Physical:"), info.physical);

    virDomainFree(dom);
    return ret;
}

2519 2520 2521 2522 2523
/*
 * "domblklist" command
 */
static const vshCmdInfo info_domblklist[] = {
    {"help", N_("list all domain blocks")},
2524
    {"desc", N_("Get the summary of block devices for a domain.")},
2525 2526 2527 2528 2529 2530 2531
    {NULL, NULL}
};

static const vshCmdOptDef opts_domblklist[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"inactive", VSH_OT_BOOL, 0,
     N_("get inactive rather than running configuration")},
2532 2533
    {"details", VSH_OT_BOOL, 0,
     N_("additionally display the type and device value")},
2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548
    {NULL, 0, 0, NULL}
};

static bool
cmdDomblklist(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    bool ret = false;
    unsigned int flags = 0;
    char *xml = NULL;
    xmlDocPtr xmldoc = NULL;
    xmlXPathContextPtr ctxt = NULL;
    int ndisks;
    xmlNodePtr *disks = NULL;
    int i;
2549
    bool details = false;
2550 2551 2552 2553

    if (vshCommandOptBool(cmd, "inactive"))
        flags |= VIR_DOMAIN_XML_INACTIVE;

2554 2555
    details = vshCommandOptBool(cmd, "details");

2556 2557 2558 2559 2560 2561 2562 2563 2564 2565
    if (!vshConnectionUsability(ctl, ctl->conn))
        return false;

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
        return false;

    xml = virDomainGetXMLDesc(dom, flags);
    if (!xml)
        goto cleanup;

2566
    xmldoc = virXMLParseStringCtxt(xml, _("(domain_definition)"), &ctxt);
2567 2568 2569 2570 2571 2572 2573
    if (!xmldoc)
        goto cleanup;

    ndisks = virXPathNodeSet("./devices/disk", ctxt, &disks);
    if (ndisks < 0)
        goto cleanup;

2574 2575 2576 2577 2578 2579
    if (details)
        vshPrint(ctl, "%-10s %-10s %-10s %s\n", _("Type"),
                 _("Device"), _("Target"), _("Source"));
    else
        vshPrint(ctl, "%-10s %s\n", _("Target"), _("Source"));

2580 2581 2582
    vshPrint(ctl, "------------------------------------------------\n");

    for (i = 0; i < ndisks; i++) {
2583 2584
        char *type;
        char *device;
2585 2586 2587 2588
        char *target;
        char *source;

        ctxt->node = disks[i];
2589 2590 2591 2592 2593 2594

        if (details) {
            type = virXPathString("string(./@type)", ctxt);
            device = virXPathString("string(./@device)", ctxt);
        }

2595 2596 2597 2598 2599 2600 2601 2602 2603
        target = virXPathString("string(./target/@dev)", ctxt);
        if (!target) {
            vshError(ctl, "unable to query block list");
            goto cleanup;
        }
        source = virXPathString("string(./source/@file"
                                "|./source/@dev"
                                "|./source/@dir"
                                "|./source/@name)", ctxt);
2604 2605 2606 2607 2608 2609 2610 2611 2612
        if (details) {
            vshPrint(ctl, "%-10s %-10s %-10s %s\n", type, device,
                     target, source ? source : "-");
            VIR_FREE(type);
            VIR_FREE(device);
        } else {
            vshPrint(ctl, "%-10s %s\n", target, source ? source : "-");
        }

2613 2614 2615 2616
        VIR_FREE(target);
        VIR_FREE(source);
    }

A
Alex Jia 已提交
2617
    ret = true;
2618 2619 2620 2621

cleanup:
    VIR_FREE(disks);
    virDomainFree(dom);
2622 2623 2624
    VIR_FREE(xml);
    xmlFreeDoc(xmldoc);
    xmlXPathFreeContext(ctxt);
2625 2626 2627
    return ret;
}

2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677
/*
 * "domiflist" command
 */
static const vshCmdInfo info_domiflist[] = {
    {"help", N_("list all domain virtual interfaces")},
    {"desc", N_("Get the summary of virtual interfaces for a domain.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_domiflist[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"inactive", VSH_OT_BOOL, 0,
     N_("get inactive rather than running configuration")},
    {NULL, 0, 0, NULL}
};

static bool
cmdDomiflist(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    bool ret = false;
    unsigned int flags = 0;
    char *xml = NULL;
    xmlDocPtr xmldoc = NULL;
    xmlXPathContextPtr ctxt = NULL;
    int ninterfaces;
    xmlNodePtr *interfaces = NULL;
    int i;

    if (vshCommandOptBool(cmd, "inactive"))
        flags |= VIR_DOMAIN_XML_INACTIVE;

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

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
        return false;

    xml = virDomainGetXMLDesc(dom, flags);
    if (!xml)
        goto cleanup;

    xmldoc = virXMLParseStringCtxt(xml, _("(domain_definition)"), &ctxt);
    if (!xmldoc)
        goto cleanup;

    ninterfaces = virXPathNodeSet("./devices/interface", ctxt, &interfaces);
    if (ninterfaces < 0)
        goto cleanup;

T
Taku Izumi 已提交
2678 2679
    vshPrint(ctl, "%-10s %-10s %-10s %-11s %s\n", _("Interface"), _("Type"),
             _("Source"), _("Model"), _("MAC"));
2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700
    vshPrint(ctl, "-------------------------------------------------------\n");

    for (i = 0; i < ninterfaces; i++) {
        char *type = NULL;
        char *source = NULL;
        char *target = NULL;
        char *model = NULL;
        char *mac = NULL;

        ctxt->node = interfaces[i];
        type = virXPathString("string(./@type)", ctxt);

        source = virXPathString("string(./source/@bridge"
                                "|./source/@dev"
                                "|./source/@network"
                                "|./source/@name)", ctxt);

        target = virXPathString("string(./target/@dev)", ctxt);
        model = virXPathString("string(./model/@type)", ctxt);
        mac = virXPathString("string(./mac/@address)", ctxt);

T
Taku Izumi 已提交
2701
        vshPrint(ctl, "%-10s %-10s %-10s %-11s %-10s\n",
2702
                 target ? target : "-",
T
Taku Izumi 已提交
2703 2704
                 type,
                 source ? source : "-",
2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725
                 model ? model : "-",
                 mac ? mac : "-");

        VIR_FREE(type);
        VIR_FREE(source);
        VIR_FREE(target);
        VIR_FREE(model);
        VIR_FREE(mac);
    }

    ret = true;

cleanup:
    VIR_FREE(interfaces);
    virDomainFree(dom);
    VIR_FREE(xml);
    xmlFreeDoc(xmldoc);
    xmlXPathFreeContext(ctxt);
    return ret;
}

2726 2727 2728
/*
 * "suspend" command
 */
2729
static const vshCmdInfo info_suspend[] = {
2730 2731
    {"help", N_("suspend a domain")},
    {"desc", N_("Suspend a running domain.")},
2732
    {NULL, NULL}
2733 2734
};

2735
static const vshCmdOptDef opts_suspend[] = {
2736
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
2737
    {NULL, 0, 0, NULL}
2738 2739
};

E
Eric Blake 已提交
2740
static bool
2741
cmdSuspend(vshControl *ctl, const vshCmd *cmd)
2742
{
2743
    virDomainPtr dom;
2744
    const char *name;
E
Eric Blake 已提交
2745
    bool ret = true;
2746

2747
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
2748
        return false;
2749

J
Jim Meyering 已提交
2750
    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
E
Eric Blake 已提交
2751
        return false;
2752 2753

    if (virDomainSuspend(dom) == 0) {
2754
        vshPrint(ctl, _("Domain %s suspended\n"), name);
2755
    } else {
2756
        vshError(ctl, _("Failed to suspend domain %s"), name);
E
Eric Blake 已提交
2757
        ret = false;
2758
    }
2759

2760 2761 2762 2763
    virDomainFree(dom);
    return ret;
}

2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834
/*
 * "dompmsuspend" command
 */
static const vshCmdInfo info_dom_pm_suspend[] = {
    {"help", N_("suspend a domain for a given time duration")},
    {"desc", N_("Suspend a running domain for a given time duration.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_dom_pm_suspend[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"duration", VSH_OT_INT, VSH_OFLAG_REQ_OPT, N_("duration in seconds")},
    {"target", VSH_OT_STRING, VSH_OFLAG_REQ, N_("mem(Suspend-to-RAM), "
                                                "disk(Suspend-to-Disk), "
                                                "hybrid(Hybrid-Suspend)")},
    {NULL, 0, 0, NULL}
};

static bool
cmdDomPMSuspend(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    const char *name;
    bool ret = false;
    const char *target = NULL;
    unsigned int suspendTarget;
    unsigned long long duration = 0;

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

    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
        return false;

    if (vshCommandOptULongLong(cmd, "duration", &duration) < 0) {
        vshError(ctl, _("Invalid duration argument"));
        goto cleanup;
    }

    if (vshCommandOptString(cmd, "target", &target) < 0) {
        vshError(ctl, _("Invalid target argument"));
        goto cleanup;
    }

    if (STREQ(target, "mem"))
        suspendTarget = VIR_NODE_SUSPEND_TARGET_MEM;
    else if (STREQ(target, "disk"))
        suspendTarget = VIR_NODE_SUSPEND_TARGET_DISK;
    else if (STREQ(target, "hybrid"))
        suspendTarget = VIR_NODE_SUSPEND_TARGET_HYBRID;
    else {
        vshError(ctl, "%s", _("Invalid target"));
        goto cleanup;
    }

    if (virDomainPMSuspendForDuration(dom, suspendTarget, duration, 0) < 0) {
        vshError(ctl, _("Domain %s could not be suspended"),
                 virDomainGetName(dom));
        goto cleanup;
    }

    vshPrint(ctl, _("Domain %s successfully suspended"),
             virDomainGetName(dom));

    ret = true;

cleanup:
    virDomainFree(dom);
    return ret;
}

2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880
/*
 * "dompmwakeup" command
 */

static const vshCmdInfo info_dom_pm_wakeup[] = {
    {"help", N_("wakeup a domain suspended by dompmsuspend command")},
    {"desc", N_("Wakeup a domain previously suspended "
                "by dompmsuspend command.")},
    {NULL, NULL}
};

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

static bool
cmdDomPMWakeup(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    const char *name;
    bool ret = false;
    unsigned int flags = 0;

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

    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
        return false;

    if (virDomainPMWakeup(dom, flags) < 0) {
        vshError(ctl, _("Domain %s could not be woken up"),
                 virDomainGetName(dom));
        goto cleanup;
    }

    vshPrint(ctl, _("Domain %s successfully woken up"),
             virDomainGetName(dom));

    ret = true;

cleanup:
    virDomainFree(dom);
    return ret;
}

2881 2882 2883
/*
 * "create" command
 */
2884
static const vshCmdInfo info_create[] = {
2885 2886
    {"help", N_("create a domain from an XML file")},
    {"desc", N_("Create a domain.")},
2887 2888 2889
    {NULL, NULL}
};

2890
static const vshCmdOptDef opts_create[] = {
2891
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing an XML domain description")},
2892
#ifndef WIN32
2893
    {"console", VSH_OT_BOOL, 0, N_("attach to console after creation")},
2894
#endif
2895
    {"paused", VSH_OT_BOOL, 0, N_("leave the guest paused after creation")},
2896
    {"autodestroy", VSH_OT_BOOL, 0, N_("automatically destroy the guest when virsh disconnects")},
2897 2898 2899
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
2900
static bool
2901
cmdCreate(vshControl *ctl, const vshCmd *cmd)
2902 2903
{
    virDomainPtr dom;
2904
    const char *from = NULL;
E
Eric Blake 已提交
2905
    bool ret = true;
2906
    char *buffer;
2907
#ifndef WIN32
2908
    bool console = vshCommandOptBool(cmd, "console");
2909
#endif
2910
    unsigned int flags = VIR_DOMAIN_NONE;
2911

2912
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
2913
        return false;
2914

2915
    if (vshCommandOptString(cmd, "file", &from) <= 0)
E
Eric Blake 已提交
2916
        return false;
2917

2918
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
E
Eric Blake 已提交
2919
        return false;
2920

2921 2922
    if (vshCommandOptBool(cmd, "paused"))
        flags |= VIR_DOMAIN_START_PAUSED;
2923 2924
    if (vshCommandOptBool(cmd, "autodestroy"))
        flags |= VIR_DOMAIN_START_AUTODESTROY;
2925 2926

    dom = virDomainCreateXML(ctl->conn, buffer, flags);
2927
    VIR_FREE(buffer);
2928

2929
    if (dom != NULL) {
2930
        vshPrint(ctl, _("Domain %s created from %s\n"),
2931
                 virDomainGetName(dom), from);
2932
#ifndef WIN32
2933
        if (console)
2934
            cmdRunConsole(ctl, dom, NULL, 0);
2935
#endif
2936
        virDomainFree(dom);
2937
    } else {
2938
        vshError(ctl, _("Failed to create domain from %s"), from);
E
Eric Blake 已提交
2939
        ret = false;
2940 2941 2942 2943
    }
    return ret;
}

2944 2945 2946
/*
 * "define" command
 */
2947
static const vshCmdInfo info_define[] = {
2948 2949
    {"help", N_("define (but don't start) a domain from an XML file")},
    {"desc", N_("Define a domain.")},
2950 2951 2952
    {NULL, NULL}
};

2953
static const vshCmdOptDef opts_define[] = {
2954
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing an XML domain description")},
2955 2956 2957
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
2958
static bool
2959
cmdDefine(vshControl *ctl, const vshCmd *cmd)
2960 2961
{
    virDomainPtr dom;
2962
    const char *from = NULL;
E
Eric Blake 已提交
2963
    bool ret = true;
2964
    char *buffer;
2965

2966
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
2967
        return false;
2968

2969
    if (vshCommandOptString(cmd, "file", &from) <= 0)
E
Eric Blake 已提交
2970
        return false;
2971

2972
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
E
Eric Blake 已提交
2973
        return false;
2974 2975

    dom = virDomainDefineXML(ctl->conn, buffer);
2976
    VIR_FREE(buffer);
2977

2978
    if (dom != NULL) {
2979
        vshPrint(ctl, _("Domain %s defined from %s\n"),
2980
                 virDomainGetName(dom), from);
2981
        virDomainFree(dom);
2982
    } else {
2983
        vshError(ctl, _("Failed to define domain from %s"), from);
E
Eric Blake 已提交
2984
        ret = false;
2985 2986 2987 2988 2989 2990 2991
    }
    return ret;
}

/*
 * "undefine" command
 */
2992
static const vshCmdInfo info_undefine[] = {
2993 2994 2995
    {"help", N_("undefine a domain")},
    {"desc",
     N_("Undefine an inactive domain, or convert persistent to transient.")},
2996 2997 2998
    {NULL, NULL}
};

2999
static const vshCmdOptDef opts_undefine[] = {
3000
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name or uuid")},
3001
    {"managed-save", VSH_OT_BOOL, 0, N_("remove domain managed state file")},
3002 3003 3004 3005 3006 3007 3008
    {"storage", VSH_OT_DATA, VSH_OFLAG_NONE,
     N_("remove associated storage volumes (comma separated list of targets "
        "or source paths) (see domblklist)")},
    {"remove-all-storage", VSH_OT_BOOL, 0,
     N_("remove all associated storage volumes (use with caution)")},
    {"wipe-storage", VSH_OT_BOOL, VSH_OFLAG_NONE,
     N_("wipe data on the removed volumes")},
3009 3010
    {"snapshots-metadata", VSH_OT_BOOL, 0,
     N_("remove all domain snapshot metadata, if inactive")},
3011 3012 3013
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
3014
static bool
3015
cmdUndefine(vshControl *ctl, const vshCmd *cmd)
3016 3017
{
    virDomainPtr dom;
3018
    bool ret = false;
3019
    const char *name = NULL;
3020
    /* Flags to attempt.  */
E
Eric Blake 已提交
3021
    unsigned int flags = 0;
3022 3023 3024
    /* User-requested actions.  */
    bool managed_save = vshCommandOptBool(cmd, "managed-save");
    bool snapshots_metadata = vshCommandOptBool(cmd, "snapshots-metadata");
3025 3026 3027
    bool wipe_storage = vshCommandOptBool(cmd, "wipe-storage");
    bool remove_storage = false;
    bool remove_all_storage = vshCommandOptBool(cmd, "remove-all-storage");
3028
    /* Positive if these items exist.  */
3029
    int has_managed_save = 0;
3030 3031 3032 3033 3034
    int has_snapshots_metadata = 0;
    int has_snapshots = 0;
    /* True if undefine will not strand data, even on older servers.  */
    bool managed_save_safe = false;
    bool snapshots_safe = false;
3035
    int rc = -1;
3036
    int running;
3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053
    /* list of volumes to remove along with this domain */
    const char *volumes_arg = NULL;
    char *volumes = NULL;
    char **volume_tokens = NULL;
    char *volume_tok = NULL;
    int nvolume_tokens = 0;
    char *def = NULL;
    char *source = NULL;
    char *target = NULL;
    int vol_i;
    int tok_i;
    xmlDocPtr doc = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlNodePtr *vol_nodes = NULL;
    int nvolumes = 0;
    virStorageVolPtr vol = NULL;
    bool vol_del_failed = false;
3054

3055
    if (managed_save) {
3056
        flags |= VIR_DOMAIN_UNDEFINE_MANAGED_SAVE;
3057 3058 3059 3060 3061 3062
        managed_save_safe = true;
    }
    if (snapshots_metadata) {
        flags |= VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA;
        snapshots_safe = true;
    }
3063

3064
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
3065
        return false;
3066

3067
    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
E
Eric Blake 已提交
3068
        return false;
3069

3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080
    /* check if a string that should contain list of volumes to remove is present */
    if (vshCommandOptString(cmd, "storage", &volumes_arg) > 0) {
        volumes = vshStrdup(ctl, volumes_arg);

        if (remove_all_storage) {
            vshError(ctl, _("Specified both --storage and --remove-all-storage"));
            goto cleanup;
        }
        remove_storage = true;
   }

3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099
    /* Do some flag manipulation.  The goal here is to disable bits
     * from flags to reduce the likelihood of a server rejecting
     * unknown flag bits, as well as to track conditions which are
     * safe by default for the given hypervisor and server version.  */
    running = virDomainIsActive(dom);
    if (running < 0) {
        virshReportError(ctl);
        goto cleanup;
    }
    if (!running) {
        /* Undefine with snapshots only fails for inactive domains,
         * and managed save only exists on inactive domains; if
         * running, then we don't want to remove anything.  */
        has_managed_save = virDomainHasManagedSaveImage(dom, 0);
        if (has_managed_save < 0) {
            if (last_error->code != VIR_ERR_NO_SUPPORT) {
                virshReportError(ctl);
                goto cleanup;
            }
3100 3101
            virFreeError(last_error);
            last_error = NULL;
3102
            has_managed_save = 0;
3103 3104
        }

3105 3106
        has_snapshots = virDomainSnapshotNum(dom, 0);
        if (has_snapshots < 0) {
3107 3108
            if (last_error->code != VIR_ERR_NO_SUPPORT) {
                virshReportError(ctl);
3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120
                goto cleanup;
            }
            virFreeError(last_error);
            last_error = NULL;
            has_snapshots = 0;
        }
        if (has_snapshots) {
            has_snapshots_metadata
                = virDomainSnapshotNum(dom, VIR_DOMAIN_SNAPSHOT_LIST_METADATA);
            if (has_snapshots_metadata < 0) {
                /* The server did not know the new flag, assume that all
                   snapshots have metadata.  */
3121 3122
                virFreeError(last_error);
                last_error = NULL;
3123 3124 3125 3126 3127
                has_snapshots_metadata = has_snapshots;
            } else {
                /* The server knew the new flag, all aspects of
                 * undefineFlags are safe.  */
                managed_save_safe = snapshots_safe = true;
3128
            }
3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141
        }
    }
    if (!has_managed_save) {
        flags &= ~VIR_DOMAIN_UNDEFINE_MANAGED_SAVE;
        managed_save_safe = true;
    }
    if (has_snapshots == 0) {
        snapshots_safe = true;
    }
    if (has_snapshots_metadata == 0) {
        flags &= ~VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA;
        snapshots_safe = true;
    }
3142

3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155
    /* Stash domain description for later use */
    if (remove_storage || remove_all_storage) {
        if (running) {
            vshError(ctl, _("Storage volume deletion is supported only on stopped domains"));
            goto cleanup;
        }

        if (!(def = virDomainGetXMLDesc(dom, 0))) {
            vshError(ctl, _("Could not retrieve domain XML description"));
            goto cleanup;
        }
    }

3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169
    /* Generally we want to try the new API first.  However, while
     * virDomainUndefineFlags was introduced at the same time as
     * VIR_DOMAIN_UNDEFINE_MANAGED_SAVE in 0.9.4, the
     * VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA flag was not present
     * until 0.9.5; skip to piecewise emulation if we couldn't prove
     * above that the new API is safe.  */
    if (managed_save_safe && snapshots_safe) {
        rc = virDomainUndefineFlags(dom, flags);
        if (rc == 0 || (last_error->code != VIR_ERR_NO_SUPPORT &&
                        last_error->code != VIR_ERR_INVALID_ARG))
            goto out;
        virFreeError(last_error);
        last_error = NULL;
    }
3170

3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182
    /* The new API is unsupported or unsafe; fall back to doing things
     * piecewise.  */
    if (has_managed_save) {
        if (!managed_save) {
            vshError(ctl, "%s",
                     _("Refusing to undefine while domain managed save "
                       "image exists"));
            goto cleanup;
        }
        if (virDomainManagedSaveRemove(dom, 0) < 0) {
            virshReportError(ctl);
            goto cleanup;
3183 3184 3185
        }
    }

3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199
    /* No way to emulate deletion of just snapshot metadata
     * without support for the newer flags.  Oh well.  */
    if (has_snapshots_metadata) {
        vshError(ctl,
                 snapshots_metadata ?
                 _("Unable to remove metadata of %d snapshots") :
                 _("Refusing to undefine while %d snapshots exist"),
                 has_snapshots_metadata);
        goto cleanup;
    }

    rc = virDomainUndefine(dom);

out:
3200
    if (rc == 0) {
3201
        vshPrint(ctl, _("Domain %s has been undefined\n"), name);
3202
        ret = true;
3203
    } else {
3204
        vshError(ctl, _("Failed to undefine domain %s"), name);
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
        goto cleanup;
    }

    /* try to undefine storage volumes associated with this domain, if it's requested */
    if (remove_storage || remove_all_storage) {
        ret = false;

        /* tokenize the string from user and save it's parts into an array */
        if (volumes) {
            /* count the delimiters */
            volume_tok = volumes;
            nvolume_tokens = 1; /* we need at least one member */
            while (*volume_tok) {
                if (*volume_tok == ',')
                    nvolume_tokens++;
                volume_tok++;
            }

            volume_tokens = vshCalloc(ctl, nvolume_tokens,  sizeof(char *));

            /* tokenize the input string */
            nvolume_tokens = 0;
            volume_tok = volumes;
            do {
                volume_tokens[nvolume_tokens] = strsep(&volume_tok, ",");
                nvolume_tokens++;
            } while (volume_tok);
        }

        doc = virXMLParseStringCtxt(def, _("(domain_definition)"), &ctxt);
        if (!doc)
            goto cleanup;

        nvolumes = virXPathNodeSet("./devices/disk", ctxt, &vol_nodes);

        if (nvolumes < 0)
            goto cleanup;

        for (vol_i = 0; vol_i < nvolumes; vol_i++) {
            ctxt->node = vol_nodes[vol_i];
            VIR_FREE(target);
            VIR_FREE(source);
            if (vol) {
                virStorageVolFree(vol);
                vol = NULL;
            }

            /* get volume source and target paths */
            if (!(target = virXPathString("string(./target/@dev)", ctxt))) {
                vshError(ctl, _("Failed to enumerate devices"));
                goto cleanup;
            }

            if (!(source = virXPathString("string("
                                          "./source/@file|"
                                          "./source/@dir|"
                                          "./source/@name|"
                                          "./source/@dev)", ctxt)) &&
                virGetLastError())
                goto cleanup;

            /* lookup if volume was selected by user */
            if (volumes) {
                volume_tok = NULL;
                for (tok_i = 0; tok_i < nvolume_tokens; tok_i++) {
                    if (volume_tokens[tok_i] &&
                        (STREQ_NULLABLE(volume_tokens[tok_i], target) ||
                         STREQ_NULLABLE(volume_tokens[tok_i], source))) {
                        volume_tok = volume_tokens[tok_i];
                        volume_tokens[tok_i] = NULL;
                        break;
                    }
                }
                if (!volume_tok)
                    continue;
            }

            if (!source)
                continue;

            if (!(vol = virStorageVolLookupByPath(ctl->conn, source))) {
                vshPrint(ctl,
                         _("Storage volume '%s'(%s) is not managed by libvirt. "
                           "Remove it manually.\n"), target, source);
                virResetLastError();
                continue;
            }

            if (wipe_storage) {
                vshPrint(ctl, _("Wiping volume '%s'(%s) ... "), target, source);
                fflush(stdout);
                if (virStorageVolWipe(vol, 0) < 0) {
                    vshError(ctl, _("Failed! Volume not removed."));
                    vol_del_failed = true;
                    continue;
                } else {
                    vshPrint(ctl, _("Done.\n"));
                }
            }

            /* delete the volume */
            if (virStorageVolDelete(vol, 0) < 0) {
                vshError(ctl, _("Failed to remove storage volume '%s'(%s)"),
                         target, source);
                vol_del_failed = true;
            }
            vshPrint(ctl, _("Volume '%s' removed.\n"), volume_tok?volume_tok:source);
        }

        /* print volumes specified by user that were not found in domain definition */
        if (volumes) {
            for (tok_i = 0; tok_i < nvolume_tokens; tok_i++) {
                if (volume_tokens[tok_i])
                    vshPrint(ctl, _("Volume '%s' was not found in domain's "
                                    "definition.\n"),
                             volume_tokens[tok_i]);
            }
        }

        if (!vol_del_failed)
            ret = true;
3326 3327
    }

3328
cleanup:
3329 3330 3331 3332 3333 3334
    VIR_FREE(source);
    VIR_FREE(target);
    VIR_FREE(volumes);
    VIR_FREE(volume_tokens);
    VIR_FREE(def);
    VIR_FREE(vol_nodes);
3335 3336
    if (vol)
        virStorageVolFree(vol);
3337 3338
    xmlFreeDoc(doc);
    xmlXPathFreeContext(ctxt);
3339
    virDomainFree(dom);
3340 3341 3342 3343 3344 3345 3346
    return ret;
}


/*
 * "start" command
 */
3347
static const vshCmdInfo info_start[] = {
3348
    {"help", N_("start a (previously defined) inactive domain")},
3349 3350 3351
    {"desc", N_("Start a domain, either from the last managedsave\n"
                "    state, or via a fresh boot if no managedsave state\n"
                "    is present.")},
3352 3353 3354
    {NULL, NULL}
};

3355
static const vshCmdOptDef opts_start[] = {
3356
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("name of the inactive domain")},
3357
#ifndef WIN32
3358
    {"console", VSH_OT_BOOL, 0, N_("attach to console after creation")},
3359
#endif
E
Eric Blake 已提交
3360
    {"paused", VSH_OT_BOOL, 0, N_("leave the guest paused after creation")},
3361 3362
    {"autodestroy", VSH_OT_BOOL, 0,
     N_("automatically destroy the guest when virsh disconnects")},
3363 3364
    {"bypass-cache", VSH_OT_BOOL, 0,
     N_("avoid file system cache when loading")},
3365 3366
    {"force-boot", VSH_OT_BOOL, 0,
     N_("force fresh boot by discarding any managed save")},
3367 3368 3369
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
3370
static bool
3371
cmdStart(vshControl *ctl, const vshCmd *cmd)
3372 3373
{
    virDomainPtr dom;
3374
    bool ret = false;
3375
#ifndef WIN32
3376
    bool console = vshCommandOptBool(cmd, "console");
3377
#endif
E
Eric Blake 已提交
3378
    unsigned int flags = VIR_DOMAIN_NONE;
3379
    int rc;
3380

3381
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
3382
        return false;
3383

3384 3385
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, NULL,
                                      VSH_BYNAME | VSH_BYUUID)))
E
Eric Blake 已提交
3386
        return false;
3387 3388

    if (virDomainGetID(dom) != (unsigned int)-1) {
3389
        vshError(ctl, "%s", _("Domain is already active"));
3390
        virDomainFree(dom);
E
Eric Blake 已提交
3391
        return false;
3392 3393
    }

E
Eric Blake 已提交
3394 3395
    if (vshCommandOptBool(cmd, "paused"))
        flags |= VIR_DOMAIN_START_PAUSED;
3396 3397
    if (vshCommandOptBool(cmd, "autodestroy"))
        flags |= VIR_DOMAIN_START_AUTODESTROY;
3398 3399
    if (vshCommandOptBool(cmd, "bypass-cache"))
        flags |= VIR_DOMAIN_START_BYPASS_CACHE;
3400 3401
    if (vshCommandOptBool(cmd, "force-boot"))
        flags |= VIR_DOMAIN_START_FORCE_BOOT;
E
Eric Blake 已提交
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
    /* We can emulate force boot, even for older servers that reject it.  */
    if (flags & VIR_DOMAIN_START_FORCE_BOOT) {
        if (virDomainCreateWithFlags(dom, flags) == 0)
            goto started;
        if (last_error->code != VIR_ERR_NO_SUPPORT &&
            last_error->code != VIR_ERR_INVALID_ARG) {
            virshReportError(ctl);
            goto cleanup;
        }
        virFreeError(last_error);
        last_error = NULL;
        rc = virDomainHasManagedSaveImage(dom, 0);
        if (rc < 0) {
            /* No managed save image to remove */
            virFreeError(last_error);
            last_error = NULL;
        } else if (rc > 0) {
            if (virDomainManagedSaveRemove(dom, 0) < 0) {
                virshReportError(ctl);
                goto cleanup;
            }
        }
        flags &= ~VIR_DOMAIN_START_FORCE_BOOT;
    }

E
Eric Blake 已提交
3428 3429
    /* Prefer older API unless we have to pass a flag.  */
    if ((flags ? virDomainCreateWithFlags(dom, flags)
3430
         : virDomainCreate(dom)) < 0) {
3431
        vshError(ctl, _("Failed to start domain %s"), virDomainGetName(dom));
3432
        goto cleanup;
3433
    }
3434 3435 3436 3437 3438

started:
    vshPrint(ctl, _("Domain %s started\n"),
             virDomainGetName(dom));
#ifndef WIN32
3439
    if (console && !cmdRunConsole(ctl, dom, NULL, 0))
3440 3441 3442 3443 3444 3445
        goto cleanup;
#endif

    ret = true;

cleanup:
3446
    virDomainFree(dom);
3447 3448 3449
    return ret;
}

3450 3451 3452
/*
 * "save" command
 */
3453
static const vshCmdInfo info_save[] = {
3454
    {"help", N_("save a domain state to a file")},
E
Eric Blake 已提交
3455
    {"desc", N_("Save the RAM state of a running domain.")},
3456
    {NULL, NULL}
3457 3458
};

3459
static const vshCmdOptDef opts_save[] = {
3460
    {"bypass-cache", VSH_OT_BOOL, 0, N_("avoid file system cache when saving")},
3461 3462
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("where to save the data")},
3463 3464
    {"xml", VSH_OT_STRING, 0,
     N_("filename containing updated XML for the target")},
3465 3466
    {"running", VSH_OT_BOOL, 0, N_("set domain to be running on restore")},
    {"paused", VSH_OT_BOOL, 0, N_("set domain to be paused on restore")},
3467
    {"verbose", VSH_OT_BOOL, 0, N_("display the progress of save")},
3468
    {NULL, 0, 0, NULL}
3469 3470
};

3471 3472
static void
doSave(void *opaque)
3473
{
3474 3475 3476 3477 3478
    vshCtrlData *data = opaque;
    vshControl *ctl = data->ctl;
    const vshCmd *cmd = data->cmd;
    char ret = '1';
    virDomainPtr dom = NULL;
3479 3480
    const char *name = NULL;
    const char *to = NULL;
E
Eric Blake 已提交
3481
    unsigned int flags = 0;
3482 3483
    const char *xmlfile = NULL;
    char *xml = NULL;
3484 3485 3486 3487 3488 3489
    sigset_t sigmask, oldsigmask;

    sigemptyset(&sigmask);
    sigaddset(&sigmask, SIGINT);
    if (pthread_sigmask(SIG_BLOCK, &sigmask, &oldsigmask) < 0)
        goto out_sig;
3490

3491
    if (!vshConnectionUsability(ctl, ctl->conn))
3492
        goto out;
3493

3494
    if (vshCommandOptString(cmd, "file", &to) <= 0)
3495
        goto out;
3496

3497 3498
    if (vshCommandOptBool(cmd, "bypass-cache"))
        flags |= VIR_DOMAIN_SAVE_BYPASS_CACHE;
3499 3500 3501 3502
    if (vshCommandOptBool(cmd, "running"))
        flags |= VIR_DOMAIN_SAVE_RUNNING;
    if (vshCommandOptBool(cmd, "paused"))
        flags |= VIR_DOMAIN_SAVE_PAUSED;
3503

3504 3505
    if (vshCommandOptString(cmd, "xml", &xmlfile) < 0) {
        vshError(ctl, "%s", _("malformed xml argument"));
3506
        goto out;
3507 3508
    }

J
Jim Meyering 已提交
3509
    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
3510
        goto out;
3511

3512 3513
    if (xmlfile &&
        virFileReadAll(xmlfile, 8192, &xml) < 0)
3514
        goto out;
3515 3516 3517

    if (((flags || xml)
         ? virDomainSaveFlags(dom, to, xml, flags)
3518
         : virDomainSave(dom, to)) < 0) {
3519
        vshError(ctl, _("Failed to save domain %s to %s"), name, to);
3520
        goto out;
3521
    }
3522

3523
    ret = '0';
3524

3525 3526 3527 3528
out:
    pthread_sigmask(SIG_SETMASK, &oldsigmask, NULL);
out_sig:
    if (dom) virDomainFree (dom);
3529
    VIR_FREE(xml);
3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550
    ignore_value(safewrite(data->writefd, &ret, sizeof(ret)));
}

static bool
cmdSave(vshControl *ctl, const vshCmd *cmd)
{
    bool ret = false;
    virDomainPtr dom = NULL;
    int p[2] = {-1. -1};
    virThread workerThread;
    bool verbose = false;
    vshCtrlData data;
    const char *to = NULL;
    const char *name = NULL;

    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
        return false;

    if (vshCommandOptString(cmd, "file", &to) <= 0)
        goto cleanup;

E
Eric Blake 已提交
3551
    if (vshCommandOptBool(cmd, "verbose"))
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
        verbose = true;

    if (pipe(p) < 0)
        goto cleanup;

    data.ctl = ctl;
    data.cmd = cmd;
    data.writefd = p[1];

    if (virThreadCreate(&workerThread,
                        true,
                        doSave,
                        &data) < 0)
        goto cleanup;

    ret = vshWatchJob(ctl, dom, verbose, p[0], 0, NULL, NULL, _("Save"));

    virThreadJoin(&workerThread);

    if (ret)
        vshPrint(ctl, _("\nDomain %s saved to %s\n"), name, to);

cleanup:
    if (dom)
        virDomainFree(dom);
3577 3578 3579
    return ret;
}

3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600
/*
 * "save-image-dumpxml" command
 */
static const vshCmdInfo info_save_image_dumpxml[] = {
    {"help", N_("saved state domain information in XML")},
    {"desc", N_("Output the domain information for a saved state file,\n"
                "as an XML dump to stdout.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_save_image_dumpxml[] = {
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("saved state file to read")},
    {"security-info", VSH_OT_BOOL, 0, N_("include security sensitive information in XML dump")},
    {NULL, 0, 0, NULL}
};

static bool
cmdSaveImageDumpxml(vshControl *ctl, const vshCmd *cmd)
{
    const char *file = NULL;
    bool ret = false;
E
Eric Blake 已提交
3601
    unsigned int flags = 0;
3602 3603 3604 3605 3606 3607 3608 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 3635 3636 3637
    char *xml = NULL;

    if (vshCommandOptBool(cmd, "security-info"))
        flags |= VIR_DOMAIN_XML_SECURE;

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

    if (vshCommandOptString(cmd, "file", &file) <= 0)
        return false;

    xml = virDomainSaveImageGetXMLDesc(ctl->conn, file, flags);
    if (!xml)
        goto cleanup;

    vshPrint(ctl, "%s", xml);
    ret = true;

cleanup:
    VIR_FREE(xml);
    return ret;
}

/*
 * "save-image-define" command
 */
static const vshCmdInfo info_save_image_define[] = {
    {"help", N_("redefine the XML for a domain's saved state file")},
    {"desc", N_("Replace the domain XML associated with a saved state file")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_save_image_define[] = {
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("saved state file to modify")},
    {"xml", VSH_OT_STRING, VSH_OFLAG_REQ,
     N_("filename containing updated XML for the target")},
3638 3639
    {"running", VSH_OT_BOOL, 0, N_("set domain to be running on restore")},
    {"paused", VSH_OT_BOOL, 0, N_("set domain to be paused on restore")},
3640 3641 3642 3643 3644 3645 3646 3647 3648 3649
    {NULL, 0, 0, NULL}
};

static bool
cmdSaveImageDefine(vshControl *ctl, const vshCmd *cmd)
{
    const char *file = NULL;
    bool ret = false;
    const char *xmlfile = NULL;
    char *xml = NULL;
3650 3651 3652 3653 3654 3655
    unsigned int flags = 0;

    if (vshCommandOptBool(cmd, "running"))
        flags |= VIR_DOMAIN_SAVE_RUNNING;
    if (vshCommandOptBool(cmd, "paused"))
        flags |= VIR_DOMAIN_SAVE_PAUSED;
3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670

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

    if (vshCommandOptString(cmd, "file", &file) <= 0)
        return false;

    if (vshCommandOptString(cmd, "xml", &xmlfile) <= 0) {
        vshError(ctl, "%s", _("malformed or missing xml argument"));
        return false;
    }

    if (virFileReadAll(xmlfile, 8192, &xml) < 0)
        goto cleanup;

3671
    if (virDomainSaveImageDefineXML(ctl->conn, file, xml, flags) < 0) {
3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694
        vshError(ctl, _("Failed to update %s"), file);
        goto cleanup;
    }

    vshPrint(ctl, _("State file %s updated.\n"), file);
    ret = true;

cleanup:
    VIR_FREE(xml);
    return ret;
}

/*
 * "save-image-edit" command
 */
static const vshCmdInfo info_save_image_edit[] = {
    {"help", N_("edit XML for a domain's saved state file")},
    {"desc", N_("Edit the domain XML associated with a saved state file")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_save_image_edit[] = {
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("saved state file to edit")},
3695 3696
    {"running", VSH_OT_BOOL, 0, N_("set domain to be running on restore")},
    {"paused", VSH_OT_BOOL, 0, N_("set domain to be paused on restore")},
3697 3698 3699 3700 3701 3702 3703 3704
    {NULL, 0, 0, NULL}
};

static bool
cmdSaveImageEdit(vshControl *ctl, const vshCmd *cmd)
{
    const char *file = NULL;
    bool ret = false;
3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720
    unsigned int getxml_flags = VIR_DOMAIN_XML_SECURE;
    unsigned int define_flags = 0;

    if (vshCommandOptBool(cmd, "running"))
        define_flags |= VIR_DOMAIN_SAVE_RUNNING;
    if (vshCommandOptBool(cmd, "paused"))
        define_flags |= VIR_DOMAIN_SAVE_PAUSED;

    /* Normally, we let the API reject mutually exclusive flags.
     * However, in the edit cycle, we let the user retry if the define
     * step fails, but the define step will always fail on invalid
     * flags, so we reject it up front to avoid looping.  */
    if (define_flags == (VIR_DOMAIN_SAVE_RUNNING | VIR_DOMAIN_SAVE_PAUSED)) {
        vshError(ctl, "%s", _("--running and --saved are mutually exclusive"));
        return false;
    }
3721 3722 3723 3724 3725 3726 3727

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

    if (vshCommandOptString(cmd, "file", &file) <= 0)
        return false;

W
Wen Congyang 已提交
3728 3729 3730 3731 3732 3733 3734 3735 3736 3737
#define EDIT_GET_XML \
    virDomainSaveImageGetXMLDesc(ctl->conn, file, getxml_flags)
#define EDIT_NOT_CHANGED \
    vshPrint(ctl, _("Saved image %s XML configuration " \
                    "not changed.\n"), file);           \
    ret = true; goto edit_cleanup;
#define EDIT_DEFINE \
    virDomainSaveImageDefineXML(ctl->conn, file, doc_edited, define_flags)
#define EDIT_FREE /* */
#include "virsh-edit.c"
3738 3739 3740 3741 3742 3743 3744 3745

    vshPrint(ctl, _("State file %s edited.\n"), file);
    ret = true;

cleanup:
    return ret;
}

3746 3747 3748 3749 3750
/*
 * "managedsave" command
 */
static const vshCmdInfo info_managedsave[] = {
    {"help", N_("managed save of a domain state")},
3751 3752 3753 3754
    {"desc", N_("Save and destroy a running domain, so it can be restarted from\n"
                "    the same state at a later time.  When the virsh 'start'\n"
                "    command is next run for the domain, it will automatically\n"
                "    be started from this saved state.")},
3755 3756 3757 3758
    {NULL, NULL}
};

static const vshCmdOptDef opts_managedsave[] = {
3759
    {"bypass-cache", VSH_OT_BOOL, 0, N_("avoid file system cache when saving")},
3760
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
3761 3762
    {"running", VSH_OT_BOOL, 0, N_("set domain to be running on next start")},
    {"paused", VSH_OT_BOOL, 0, N_("set domain to be paused on next start")},
3763
    {"verbose", VSH_OT_BOOL, 0, N_("display the progress of save")},
3764 3765 3766
    {NULL, 0, 0, NULL}
};

3767 3768
static void
doManagedsave(void *opaque)
3769
{
3770 3771 3772 3773 3774
    char ret = '1';
    vshCtrlData *data = opaque;
    vshControl *ctl = data->ctl;
    const vshCmd *cmd = data->cmd;
    virDomainPtr dom = NULL;
3775
    const char *name;
E
Eric Blake 已提交
3776
    unsigned int flags = 0;
3777 3778 3779 3780 3781 3782
    sigset_t sigmask, oldsigmask;

    sigemptyset(&sigmask);
    sigaddset(&sigmask, SIGINT);
    if (pthread_sigmask(SIG_BLOCK, &sigmask, &oldsigmask) < 0)
        goto out_sig;
3783

3784
    if (!vshConnectionUsability(ctl, ctl->conn))
3785
        goto out;
3786

3787 3788
    if (vshCommandOptBool(cmd, "bypass-cache"))
        flags |= VIR_DOMAIN_SAVE_BYPASS_CACHE;
3789 3790 3791 3792
    if (vshCommandOptBool(cmd, "running"))
        flags |= VIR_DOMAIN_SAVE_RUNNING;
    if (vshCommandOptBool(cmd, "paused"))
        flags |= VIR_DOMAIN_SAVE_PAUSED;
3793

3794
    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
3795
        goto out;
3796

3797
    if (virDomainManagedSave(dom, flags) < 0) {
3798
        vshError(ctl, _("Failed to save domain %s state"), name);
3799
        goto out;
3800 3801
    }

3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824
    ret = '0';
out:
    pthread_sigmask(SIG_SETMASK, &oldsigmask, NULL);
out_sig:
    if (dom)
        virDomainFree (dom);
    ignore_value(safewrite(data->writefd, &ret, sizeof(ret)));
}

static bool
cmdManagedSave(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    int p[2] = { -1, -1};
    bool ret = false;
    bool verbose = false;
    const char *name = NULL;
    vshCtrlData data;
    virThread workerThread;

    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
        return false;

E
Eric Blake 已提交
3825
    if (vshCommandOptBool(cmd, "verbose"))
3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847
        verbose = true;

    if (pipe(p) < 0)
        goto cleanup;

    data.ctl = ctl;
    data.cmd = cmd;
    data.writefd = p[1];

    if (virThreadCreate(&workerThread,
                        true,
                        doManagedsave,
                        &data) < 0)
        goto cleanup;

    ret = vshWatchJob(ctl, dom, verbose, p[0], 0,
                      NULL, NULL, _("Managedsave"));

    virThreadJoin(&workerThread);

    if (ret)
        vshPrint(ctl, _("\nDomain %s state saved by libvirt\n"), name);
3848 3849

cleanup:
3850
    virDomainFree(dom);
3851 3852
    VIR_FORCE_CLOSE(p[0]);
    VIR_FORCE_CLOSE(p[1]);
3853 3854 3855
    return ret;
}

3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869
/*
 * "managedsave-remove" command
 */
static const vshCmdInfo info_managedsaveremove[] = {
    {"help", N_("Remove managed save of a domain")},
    {"desc", N_("Remove an existing managed save state file from a domain")},
    {NULL, NULL}
};

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

E
Eric Blake 已提交
3870
static bool
3871 3872 3873
cmdManagedSaveRemove(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
3874
    const char *name;
E
Eric Blake 已提交
3875
    bool ret = false;
3876 3877
    int hassave;

3878
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
3879
        return false;
3880 3881

    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
E
Eric Blake 已提交
3882
        return false;
3883 3884 3885

    hassave = virDomainHasManagedSaveImage(dom, 0);
    if (hassave < 0) {
3886
        vshError(ctl, "%s", _("Failed to check for domain managed save image"));
3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902
        goto cleanup;
    }

    if (hassave) {
        if (virDomainManagedSaveRemove(dom, 0) < 0) {
            vshError(ctl, _("Failed to remove managed save image for domain %s"),
                     name);
            goto cleanup;
        }
        else
            vshPrint(ctl, _("Removed managedsave image for domain %s"), name);
    }
    else
        vshPrint(ctl, _("Domain %s has no manage save image; removal skipped"),
                 name);

E
Eric Blake 已提交
3903
    ret = true;
3904 3905 3906 3907 3908 3909

cleanup:
    virDomainFree(dom);
    return ret;
}

3910 3911 3912
/*
 * "schedinfo" command
 */
3913
static const vshCmdInfo info_schedinfo[] = {
3914 3915
    {"help", N_("show/set scheduler parameters")},
    {"desc", N_("Show/Set scheduler parameters.")},
3916 3917 3918
    {NULL, NULL}
};

3919
static const vshCmdOptDef opts_schedinfo[] = {
3920 3921 3922 3923
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"set", VSH_OT_STRING, VSH_OFLAG_NONE, N_("parameter=value")},
    {"weight", VSH_OT_INT, VSH_OFLAG_NONE, N_("weight for XEN_CREDIT")},
    {"cap", VSH_OT_INT, VSH_OFLAG_NONE, N_("cap for XEN_CREDIT")},
3924 3925 3926
    {"current", VSH_OT_BOOL, 0, N_("get/set current scheduler info")},
    {"config", VSH_OT_BOOL, 0, N_("get/set value to be used on next boot")},
    {"live", VSH_OT_BOOL, 0, N_("get/set value from running domain")},
3927 3928 3929
    {NULL, 0, 0, NULL}
};

W
Wen Congyang 已提交
3930
static int
3931
cmdSchedInfoUpdate(vshControl *ctl, const vshCmd *cmd,
3932
                   virTypedParameterPtr param)
3933
{
3934
    const char *data = NULL;
3935 3936 3937

    /* Legacy 'weight' parameter */
    if (STREQ(param->field, "weight") &&
3938
        param->type == VIR_TYPED_PARAM_UINT &&
3939 3940
        vshCommandOptBool(cmd, "weight")) {
        int val;
3941
        if (vshCommandOptInt(cmd, "weight", &val) <= 0) {
3942
            vshError(ctl, "%s", _("Invalid value of weight"));
3943
            return -1;
3944
        } else {
3945
            param->value.ui = val;
3946
        }
3947
        return 1;
3948 3949
    }

3950 3951
    /* Legacy 'cap' parameter */
    if (STREQ(param->field, "cap") &&
3952
        param->type == VIR_TYPED_PARAM_UINT &&
3953 3954
        vshCommandOptBool(cmd, "cap")) {
        int val;
3955
        if (vshCommandOptInt(cmd, "cap", &val) <= 0) {
3956
            vshError(ctl, "%s", _("Invalid value of cap"));
3957
            return -1;
3958
        } else {
3959
            param->value.ui = val;
3960
        }
3961
        return 1;
3962
    }
3963

3964
    if (vshCommandOptString(cmd, "set", &data) > 0) {
3965 3966 3967
        char *val = strchr(data, '=');
        int match = 0;
        if (!val) {
3968
            vshError(ctl, "%s", _("Invalid syntax for --set, expecting name=value"));
3969
            return -1;
3970
        }
3971 3972 3973 3974 3975 3976 3977 3978 3979
        *val = '\0';
        match = STREQ(data, param->field);
        *val = '=';
        val++;

        if (!match)
            return 0;

        switch (param->type) {
3980
        case VIR_TYPED_PARAM_INT:
3981
            if (virStrToLong_i(val, NULL, 10, &param->value.i) < 0) {
3982
                vshError(ctl, "%s",
3983 3984 3985 3986
                         _("Invalid value for parameter, expecting an int"));
                return -1;
            }
            break;
3987
        case VIR_TYPED_PARAM_UINT:
3988
            if (virStrToLong_ui(val, NULL, 10, &param->value.ui) < 0) {
3989
                vshError(ctl, "%s",
3990 3991 3992 3993
                         _("Invalid value for parameter, expecting an unsigned int"));
                return -1;
            }
            break;
3994
        case VIR_TYPED_PARAM_LLONG:
3995
            if (virStrToLong_ll(val, NULL, 10, &param->value.l) < 0) {
3996
                vshError(ctl, "%s",
J
Jim Meyering 已提交
3997
                         _("Invalid value for parameter, expecting a long long"));
3998 3999 4000
                return -1;
            }
            break;
4001
        case VIR_TYPED_PARAM_ULLONG:
4002
            if (virStrToLong_ull(val, NULL, 10, &param->value.ul) < 0) {
4003
                vshError(ctl, "%s",
4004 4005 4006 4007
                         _("Invalid value for parameter, expecting an unsigned long long"));
                return -1;
            }
            break;
4008
        case VIR_TYPED_PARAM_DOUBLE:
4009
            if (virStrToDouble(val, NULL, &param->value.d) < 0) {
4010
                vshError(ctl, "%s", _("Invalid value for parameter, expecting a double"));
4011 4012 4013
                return -1;
            }
            break;
4014
        case VIR_TYPED_PARAM_BOOLEAN:
4015
            param->value.b = STREQ(val, "0") ? 0 : 1;
4016
        }
4017
        return 1;
4018
    }
4019

4020 4021
    return 0;
}
4022

4023

E
Eric Blake 已提交
4024
static bool
4025 4026 4027 4028
cmdSchedinfo(vshControl *ctl, const vshCmd *cmd)
{
    char *schedulertype;
    virDomainPtr dom;
4029
    virTypedParameterPtr params = NULL;
4030 4031 4032
    int nparams = 0;
    int update = 0;
    int i, ret;
W
Wen Congyang 已提交
4033
    bool ret_val = false;
4034
    unsigned int flags = 0;
4035 4036 4037
    bool current = vshCommandOptBool(cmd, "current");
    bool config = vshCommandOptBool(cmd, "config");
    bool live = vshCommandOptBool(cmd, "live");
4038 4039 4040 4041 4042 4043

    if (current) {
        if (live || config) {
            vshError(ctl, "%s", _("--current must be specified exclusively"));
            return false;
        }
4044
        flags = VIR_DOMAIN_AFFECT_CURRENT;
4045 4046
    } else {
        if (config)
4047
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
4048
        if (live)
4049
            flags |= VIR_DOMAIN_AFFECT_LIVE;
4050
    }
4051

4052
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
4053
        return false;
4054

4055
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
4056
        return false;
4057 4058 4059

    /* Print SchedulerType */
    schedulertype = virDomainGetSchedulerType(dom, &nparams);
4060
    if (schedulertype != NULL) {
4061
        vshPrint(ctl, "%-15s: %s\n", _("Scheduler"),
4062
             schedulertype);
4063
        VIR_FREE(schedulertype);
4064
    } else {
4065
        vshPrint(ctl, "%-15s: %s\n", _("Scheduler"), _("Unknown"));
4066
        goto cleanup;
4067 4068
    }

4069
    if (nparams) {
4070
        params = vshMalloc(ctl, sizeof(*params) * nparams);
4071

4072
        memset(params, 0, sizeof(*params) * nparams);
4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083
        if (flags || current) {
            /* We cannot query both live and config at once, so settle
               on current in that case.  If we are setting, then the
               two values should match when we re-query; otherwise, we
               report the error later.  */
            ret = virDomainGetSchedulerParametersFlags(dom, params, &nparams,
                                                       ((live && config) ? 0
                                                        : flags));
        } else {
            ret = virDomainGetSchedulerParameters(dom, params, &nparams);
        }
4084 4085 4086 4087
        if (ret == -1)
            goto cleanup;

        /* See if any params are being set */
4088
        for (i = 0; i < nparams; i++) {
4089 4090 4091 4092 4093 4094 4095 4096 4097 4098
            ret = cmdSchedInfoUpdate(ctl, cmd, &(params[i]));
            if (ret == -1)
                goto cleanup;

            if (ret == 1)
                update = 1;
        }

        /* Update parameters & refresh data */
        if (update) {
4099 4100 4101 4102 4103
            if (flags || current)
                ret = virDomainSetSchedulerParametersFlags(dom, params,
                                                           nparams, flags);
            else
                ret = virDomainSetSchedulerParameters(dom, params, nparams);
4104 4105 4106
            if (ret == -1)
                goto cleanup;

4107 4108 4109 4110 4111 4112 4113
            if (flags || current)
                ret = virDomainGetSchedulerParametersFlags(dom, params,
                                                           &nparams,
                                                           ((live && config) ? 0
                                                            : flags));
            else
                ret = virDomainGetSchedulerParameters(dom, params, &nparams);
4114 4115
            if (ret == -1)
                goto cleanup;
4116 4117 4118 4119
        } else {
            /* See if we've tried to --set var=val.  If so, the fact that
               we reach this point (with update == 0) means that "var" did
               not match any of the settable parameters.  Report the error.  */
4120 4121
            const char *var_value_pair = NULL;
            if (vshCommandOptString(cmd, "set", &var_value_pair) > 0) {
4122 4123 4124 4125
                vshError(ctl, _("invalid scheduler option: %s"),
                         var_value_pair);
                goto cleanup;
            }
4126 4127 4128 4129 4130 4131
            /* When not doing --set, --live and --config do not mix.  */
            if (live && config) {
                vshError(ctl, "%s",
                         _("cannot query both live and config at once"));
                goto cleanup;
            }
4132 4133
        }

E
Eric Blake 已提交
4134
        ret_val = true;
4135
        for (i = 0; i < nparams; i++) {
4136 4137 4138
            char *str = vshGetTypedParamValue(ctl, &params[i]);
            vshPrint(ctl, "%-15s: %s\n", params[i].field, str);
            VIR_FREE(str);
4139 4140
        }
    }
4141

4142
 cleanup:
4143
    VIR_FREE(params);
4144
    virDomainFree(dom);
4145
    return ret_val;
4146 4147
}

4148 4149 4150
/*
 * "restore" command
 */
4151
static const vshCmdInfo info_restore[] = {
4152 4153
    {"help", N_("restore a domain from a saved state in a file")},
    {"desc", N_("Restore a domain.")},
4154
    {NULL, NULL}
4155 4156
};

4157
static const vshCmdOptDef opts_restore[] = {
4158
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("the state to restore")},
4159 4160
    {"bypass-cache", VSH_OT_BOOL, 0,
     N_("avoid file system cache when restoring")},
4161 4162
    {"xml", VSH_OT_STRING, 0,
     N_("filename containing updated XML for the target")},
4163 4164
    {"running", VSH_OT_BOOL, 0, N_("restore domain into running state")},
    {"paused", VSH_OT_BOOL, 0, N_("restore domain into paused state")},
4165
    {NULL, 0, 0, NULL}
4166 4167
};

E
Eric Blake 已提交
4168
static bool
4169
cmdRestore(vshControl *ctl, const vshCmd *cmd)
4170
{
4171
    const char *from = NULL;
4172
    bool ret = false;
E
Eric Blake 已提交
4173
    unsigned int flags = 0;
4174 4175
    const char *xmlfile = NULL;
    char *xml = NULL;
4176

4177
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
4178
        return false;
4179

4180
    if (vshCommandOptString(cmd, "file", &from) <= 0)
E
Eric Blake 已提交
4181
        return false;
4182

4183 4184
    if (vshCommandOptBool(cmd, "bypass-cache"))
        flags |= VIR_DOMAIN_SAVE_BYPASS_CACHE;
4185 4186 4187 4188
    if (vshCommandOptBool(cmd, "running"))
        flags |= VIR_DOMAIN_SAVE_RUNNING;
    if (vshCommandOptBool(cmd, "paused"))
        flags |= VIR_DOMAIN_SAVE_PAUSED;
4189

4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200
    if (vshCommandOptString(cmd, "xml", &xmlfile) < 0) {
        vshError(ctl, "%s", _("malformed xml argument"));
        return false;
    }

    if (xmlfile &&
        virFileReadAll(xmlfile, 8192, &xml) < 0)
        goto cleanup;

    if (((flags || xml)
         ? virDomainRestoreFlags(ctl->conn, from, xml, flags)
4201
         : virDomainRestore(ctl->conn, from)) < 0) {
4202
        vshError(ctl, _("Failed to restore domain from %s"), from);
4203
        goto cleanup;
4204
    }
4205 4206 4207 4208 4209

    vshPrint(ctl, _("Domain restored from %s\n"), from);
    ret = true;

cleanup:
4210
    VIR_FREE(xml);
4211 4212 4213
    return ret;
}

D
Daniel Veillard 已提交
4214 4215 4216
/*
 * "dump" command
 */
4217
static const vshCmdInfo info_dump[] = {
4218 4219
    {"help", N_("dump the core of a domain to a file for analysis")},
    {"desc", N_("Core dump a domain.")},
D
Daniel Veillard 已提交
4220 4221 4222
    {NULL, NULL}
};

4223
static const vshCmdOptDef opts_dump[] = {
4224 4225
    {"live", VSH_OT_BOOL, 0, N_("perform a live core dump if supported")},
    {"crash", VSH_OT_BOOL, 0, N_("crash the domain after core dump")},
4226 4227
    {"bypass-cache", VSH_OT_BOOL, 0,
     N_("avoid file system cache when saving")},
4228
    {"reset", VSH_OT_BOOL, 0, N_("reset the domain after core dump")},
4229 4230
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("where to dump the core")},
4231
    {"verbose", VSH_OT_BOOL, 0, N_("display the progress of dump")},
4232
    {"memory-only", VSH_OT_BOOL, 0, N_("dump domain's memory only")},
D
Daniel Veillard 已提交
4233 4234 4235
    {NULL, 0, 0, NULL}
};

4236 4237
static void
doDump(void *opaque)
D
Daniel Veillard 已提交
4238
{
4239 4240 4241 4242 4243 4244
    char ret = '1';
    vshCtrlData *data = opaque;
    vshControl *ctl = data->ctl;
    const vshCmd *cmd = data->cmd;
    virDomainPtr dom = NULL;
    sigset_t sigmask, oldsigmask;
4245 4246
    const char *name = NULL;
    const char *to = NULL;
E
Eric Blake 已提交
4247
    unsigned int flags = 0;
D
Daniel Veillard 已提交
4248

4249 4250 4251 4252 4253
    sigemptyset(&sigmask);
    sigaddset(&sigmask, SIGINT);
    if (pthread_sigmask(SIG_BLOCK, &sigmask, &oldsigmask) < 0)
        goto out_sig;

4254
    if (!vshConnectionUsability(ctl, ctl->conn))
4255
        goto out;
D
Daniel Veillard 已提交
4256

4257
    if (vshCommandOptString(cmd, "file", &to) <= 0)
4258
        goto out;
D
Daniel Veillard 已提交
4259

J
Jim Meyering 已提交
4260
    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
4261
        goto out;
D
Daniel Veillard 已提交
4262

E
Eric Blake 已提交
4263
    if (vshCommandOptBool(cmd, "live"))
P
Paolo Bonzini 已提交
4264
        flags |= VIR_DUMP_LIVE;
E
Eric Blake 已提交
4265
    if (vshCommandOptBool(cmd, "crash"))
4266
        flags |= VIR_DUMP_CRASH;
4267 4268
    if (vshCommandOptBool(cmd, "bypass-cache"))
        flags |= VIR_DUMP_BYPASS_CACHE;
4269 4270
    if (vshCommandOptBool(cmd, "reset"))
        flags |= VIR_DUMP_RESET;
4271 4272
    if (vshCommandOptBool(cmd, "memory-only"))
        flags |= VIR_DUMP_MEMORY_ONLY;
4273

4274
    if (virDomainCoreDump(dom, to, flags) < 0) {
4275
        vshError(ctl, _("Failed to core dump domain %s to %s"), name, to);
4276
        goto out;
D
Daniel Veillard 已提交
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
    ret = '0';
out:
    pthread_sigmask(SIG_SETMASK, &oldsigmask, NULL);
out_sig:
    if (dom)
        virDomainFree (dom);
    ignore_value(safewrite(data->writefd, &ret, sizeof(ret)));
}

static bool
cmdDump(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    int p[2] = { -1, -1};
    bool ret = false;
    bool verbose = false;
    const char *name = NULL;
    const char *to = NULL;
    vshCtrlData data;
    virThread workerThread;

    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
        return false;

    if (vshCommandOptString(cmd, "file", &to) <= 0)
        return false;

E
Eric Blake 已提交
4306
    if (vshCommandOptBool(cmd, "verbose"))
4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327
        verbose = true;

    if (pipe(p) < 0)
        goto cleanup;

    data.ctl = ctl;
    data.cmd = cmd;
    data.writefd = p[1];

    if (virThreadCreate(&workerThread,
                        true,
                        doDump,
                        &data) < 0)
        goto cleanup;

    ret = vshWatchJob(ctl, dom, verbose, p[0], 0, NULL, NULL, _("Dump"));

    virThreadJoin(&workerThread);

    if (ret)
        vshPrint(ctl, _("\nDomain %s dumped to %s\n"), name, to);
4328 4329

cleanup:
D
Daniel Veillard 已提交
4330
    virDomainFree(dom);
4331 4332
    VIR_FORCE_CLOSE(p[0]);
    VIR_FORCE_CLOSE(p[1]);
D
Daniel Veillard 已提交
4333 4334 4335
    return ret;
}

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
static const vshCmdInfo info_screenshot[] = {
    {"help", N_("take a screenshot of a current domain console and store it "
                "into a file")},
    {"desc", N_("screenshot of a current domain console")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_screenshot[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"file", VSH_OT_DATA, VSH_OFLAG_NONE, N_("where to store the screenshot")},
    {"screen", VSH_OT_INT, VSH_OFLAG_NONE, N_("ID of a screen to take screenshot of")},
    {NULL, 0, 0, NULL}
};

static int vshStreamSink(virStreamPtr st ATTRIBUTE_UNUSED,
                         const char *bytes, size_t nbytes, void *opaque)
{
    int *fd = opaque;

    return safewrite(*fd, bytes, nbytes);
}

/**
 * Generate string: '<domain name>-<timestamp>[<extension>]'
 */
static char *
vshGenFileName(vshControl *ctl, virDomainPtr dom, const char *mime)
{
    char timestr[100];
    struct timeval cur_time;
    struct tm time_info;
    const char *ext = NULL;
    char *ret = NULL;

    /* We should be already connected, but doesn't
     * hurt to check */
    if (!vshConnectionUsability(ctl, ctl->conn))
        return NULL;

    if (!dom) {
        vshError(ctl, "%s", _("Invalid domain supplied"));
        return NULL;
    }

    if (STREQ(mime, "image/x-portable-pixmap"))
        ext = ".ppm";
    else if (STREQ(mime, "image/png"))
        ext = ".png";
    /* add mime type here */

    gettimeofday(&cur_time, NULL);
    localtime_r(&cur_time.tv_sec, &time_info);
    strftime(timestr, sizeof(timestr), "%Y-%m-%d-%H:%M:%S", &time_info);

    if (virAsprintf(&ret, "%s-%s%s", virDomainGetName(dom),
                    timestr, ext ? ext : "") < 0) {
        vshError(ctl, "%s", _("Out of memory"));
        return NULL;
    }

    return ret;
}

static bool
cmdScreenshot(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    const char *name = NULL;
    char *file = NULL;
    int fd = -1;
    virStreamPtr st = NULL;
    unsigned int screen = 0;
    unsigned int flags = 0; /* currently unused */
    int ret = false;
4410
    bool created = false;
4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449
    bool generated = false;
    char *mime = NULL;

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

    if (vshCommandOptString(cmd, "file", (const char **) &file) < 0) {
        vshError(ctl, "%s", _("file must not be empty"));
        return false;
    }

    if (vshCommandOptUInt(cmd, "screen", &screen) < 0) {
        vshError(ctl, "%s", _("invalid screen ID"));
        return false;
    }

    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
        return false;

    st = virStreamNew(ctl->conn, 0);

    mime = virDomainScreenshot(dom, st, screen, flags);
    if (!mime) {
        vshError(ctl, _("could not take a screenshot of %s"), name);
        goto cleanup;
    }

    if (!file) {
        if (!(file=vshGenFileName(ctl, dom, mime)))
            return false;
        generated = true;
    }

    if ((fd = open(file, O_WRONLY|O_CREAT|O_EXCL, 0666)) < 0) {
        if (errno != EEXIST ||
            (fd = open(file, O_WRONLY|O_TRUNC, 0666)) < 0) {
            vshError(ctl, _("cannot create file %s"), file);
            goto cleanup;
        }
4450 4451
    } else {
        created = true;
4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480
    }

    if (virStreamRecvAll(st, vshStreamSink, &fd) < 0) {
        vshError(ctl, _("could not receive data from domain %s"), name);
        goto cleanup;
    }

    if (VIR_CLOSE(fd) < 0) {
        vshError(ctl, _("cannot close file %s"), file);
        goto cleanup;
    }

    if (virStreamFinish(st) < 0) {
        vshError(ctl, _("cannot close stream on domain %s"), name);
        goto cleanup;
    }

    vshPrint(ctl, _("Screenshot saved to %s, with type of %s"), file, mime);
    ret = true;

cleanup:
    if (!ret && created)
        unlink(file);
    if (generated)
        VIR_FREE(file);
    virDomainFree(dom);
    if (st)
        virStreamFree(st);
    VIR_FORCE_CLOSE(fd);
4481
    VIR_FREE(mime);
4482 4483 4484
    return ret;
}

4485 4486 4487
/*
 * "resume" command
 */
4488
static const vshCmdInfo info_resume[] = {
4489 4490
    {"help", N_("resume a domain")},
    {"desc", N_("Resume a previously suspended domain.")},
4491
    {NULL, NULL}
4492 4493
};

4494
static const vshCmdOptDef opts_resume[] = {
4495
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
4496
    {NULL, 0, 0, NULL}
4497 4498
};

E
Eric Blake 已提交
4499
static bool
4500
cmdResume(vshControl *ctl, const vshCmd *cmd)
4501
{
4502
    virDomainPtr dom;
E
Eric Blake 已提交
4503
    bool ret = true;
4504
    const char *name;
4505

4506
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
4507
        return false;
4508

J
Jim Meyering 已提交
4509
    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
E
Eric Blake 已提交
4510
        return false;
4511 4512

    if (virDomainResume(dom) == 0) {
4513
        vshPrint(ctl, _("Domain %s resumed\n"), name);
4514
    } else {
4515
        vshError(ctl, _("Failed to resume domain %s"), name);
E
Eric Blake 已提交
4516
        ret = false;
4517
    }
4518

4519 4520 4521 4522
    virDomainFree(dom);
    return ret;
}

4523 4524 4525
/*
 * "shutdown" command
 */
4526
static const vshCmdInfo info_shutdown[] = {
4527 4528
    {"help", N_("gracefully shutdown a domain")},
    {"desc", N_("Run shutdown in the target domain.")},
4529
    {NULL, NULL}
4530 4531
};

4532
static const vshCmdOptDef opts_shutdown[] = {
4533
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
4534
    {"mode", VSH_OT_STRING, VSH_OFLAG_NONE, N_("shutdown mode: acpi|agent")},
4535
    {NULL, 0, 0, NULL}
4536 4537
};

E
Eric Blake 已提交
4538
static bool
4539
cmdShutdown(vshControl *ctl, const vshCmd *cmd)
4540
{
4541
    virDomainPtr dom;
E
Eric Blake 已提交
4542
    bool ret = true;
4543
    const char *name;
4544 4545 4546
    const char *mode = NULL;
    int flags = 0;
    int rv;
4547

4548
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
4549
        return false;
4550

4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566
    if (vshCommandOptString(cmd, "mode", &mode) < 0) {
        vshError(ctl, "%s", _("Invalid type"));
        return false;
    }

    if (mode) {
        if (STREQ(mode, "acpi")) {
            flags |= VIR_DOMAIN_SHUTDOWN_ACPI_POWER_BTN;
        } else if (STREQ(mode, "agent")) {
            flags |= VIR_DOMAIN_SHUTDOWN_GUEST_AGENT;
        } else {
            vshError(ctl, _("Unknown mode %s value, expecting 'acpi' or 'agent'"), mode);
            return false;
        }
    }

J
Jim Meyering 已提交
4567
    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
E
Eric Blake 已提交
4568
        return false;
4569

4570 4571 4572 4573 4574
    if (flags)
        rv = virDomainShutdownFlags(dom, flags);
    else
        rv = virDomainShutdown(dom);
    if (rv == 0) {
4575
        vshPrint(ctl, _("Domain %s is being shutdown\n"), name);
4576
    } else {
4577
        vshError(ctl, _("Failed to shutdown domain %s"), name);
E
Eric Blake 已提交
4578
        ret = false;
4579
    }
4580

4581 4582 4583 4584
    virDomainFree(dom);
    return ret;
}

4585 4586 4587
/*
 * "reboot" command
 */
4588
static const vshCmdInfo info_reboot[] = {
4589 4590
    {"help", N_("reboot a domain")},
    {"desc", N_("Run a reboot command in the target domain.")},
4591 4592 4593
    {NULL, NULL}
};

4594
static const vshCmdOptDef opts_reboot[] = {
4595
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
4596
    {"mode", VSH_OT_STRING, VSH_OFLAG_NONE, N_("shutdown mode: acpi|agent")},
4597 4598 4599
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
4600
static bool
4601
cmdReboot(vshControl *ctl, const vshCmd *cmd)
4602 4603
{
    virDomainPtr dom;
E
Eric Blake 已提交
4604
    bool ret = true;
4605
    const char *name;
4606 4607
    const char *mode = NULL;
    int flags = 0;
4608

4609
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
4610
        return false;
4611

4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627
    if (vshCommandOptString(cmd, "mode", &mode) < 0) {
        vshError(ctl, "%s", _("Invalid type"));
        return false;
    }

    if (mode) {
        if (STREQ(mode, "acpi")) {
            flags |= VIR_DOMAIN_SHUTDOWN_ACPI_POWER_BTN;
        } else if (STREQ(mode, "agent")) {
            flags |= VIR_DOMAIN_SHUTDOWN_GUEST_AGENT;
        } else {
            vshError(ctl, _("Unknown mode %s value, expecting 'acpi' or 'agent'"), mode);
            return false;
        }
    }

J
Jim Meyering 已提交
4628
    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
E
Eric Blake 已提交
4629
        return false;
4630

4631
    if (virDomainReboot(dom, flags) == 0) {
4632
        vshPrint(ctl, _("Domain %s is being rebooted\n"), name);
4633
    } else {
4634
        vshError(ctl, _("Failed to reboot domain %s"), name);
E
Eric Blake 已提交
4635
        ret = false;
4636 4637 4638 4639 4640 4641
    }

    virDomainFree(dom);
    return ret;
}

X
Xu He Jie 已提交
4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679
/*
 * "reset" command
 */
static const vshCmdInfo info_reset[] = {
    {"help", N_("reset a domain")},
    {"desc", N_("Reset the target domain as if by power button")},
    {NULL, NULL}
};

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

static bool
cmdReset(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    bool ret = true;
    const char *name;

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

    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
        return false;

    if (virDomainReset(dom, 0) == 0) {
        vshPrint(ctl, _("Domain %s was reset\n"), name);
    } else {
        vshError(ctl, _("Failed to reset domain %s"), name);
        ret = false;
    }

    virDomainFree(dom);
    return ret;
}

4680 4681 4682
/*
 * "destroy" command
 */
4683
static const vshCmdInfo info_destroy[] = {
4684 4685 4686
    {"help", N_("destroy (stop) a domain")},
    {"desc",
     N_("Forcefully stop a given domain, but leave its resources intact.")},
4687
    {NULL, NULL}
4688 4689
};

4690
static const vshCmdOptDef opts_destroy[] = {
4691
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
4692
    {"graceful", VSH_OT_BOOL, VSH_OFLAG_NONE, N_("terminate gracefully")},
4693
    {NULL, 0, 0, NULL}
4694 4695
};

E
Eric Blake 已提交
4696
static bool
4697
cmdDestroy(vshControl *ctl, const vshCmd *cmd)
4698
{
4699
    virDomainPtr dom;
E
Eric Blake 已提交
4700
    bool ret = true;
4701
    const char *name;
4702 4703
    unsigned int flags = 0;
    int result;
4704

4705
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
4706
        return false;
4707

J
Jim Meyering 已提交
4708
    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
E
Eric Blake 已提交
4709
        return false;
4710

4711 4712 4713 4714 4715 4716 4717 4718 4719
    if (vshCommandOptBool(cmd, "graceful"))
       flags |= VIR_DOMAIN_DESTROY_GRACEFUL;

    if (flags)
       result = virDomainDestroyFlags(dom, VIR_DOMAIN_DESTROY_GRACEFUL);
    else
       result = virDomainDestroy(dom);

    if (result == 0) {
4720
        vshPrint(ctl, _("Domain %s destroyed\n"), name);
4721
    } else {
4722
        vshError(ctl, _("Failed to destroy domain %s"), name);
E
Eric Blake 已提交
4723
        ret = false;
4724
    }
4725

4726
    virDomainFree(dom);
K
Karel Zak 已提交
4727 4728 4729 4730
    return ret;
}

/*
4731
 * "dominfo" command
K
Karel Zak 已提交
4732
 */
4733
static const vshCmdInfo info_dominfo[] = {
4734 4735
    {"help", N_("domain information")},
    {"desc", N_("Returns basic information about the domain.")},
4736
    {NULL, NULL}
K
Karel Zak 已提交
4737 4738
};

4739
static const vshCmdOptDef opts_dominfo[] = {
4740
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
4741
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
4742 4743
};

E
Eric Blake 已提交
4744
static bool
4745
cmdDominfo(vshControl *ctl, const vshCmd *cmd)
4746
{
K
Karel Zak 已提交
4747 4748
    virDomainInfo info;
    virDomainPtr dom;
4749
    virSecurityModel secmodel;
4750
    virSecurityLabelPtr seclabel;
4751
    int persistent = 0;
E
Eric Blake 已提交
4752 4753
    bool ret = true;
    int autostart;
4754
    unsigned int id;
4755
    char *str, uuid[VIR_UUID_STRING_BUFLEN];
4756
    int has_managed_save = 0;
4757

4758
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
4759
        return false;
K
Karel Zak 已提交
4760

J
Jim Meyering 已提交
4761
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
4762
        return false;
4763

4764 4765
    id = virDomainGetID(dom);
    if (id == ((unsigned int)-1))
4766
        vshPrint(ctl, "%-15s %s\n", _("Id:"), "-");
4767
    else
4768
        vshPrint(ctl, "%-15s %d\n", _("Id:"), id);
4769 4770
    vshPrint(ctl, "%-15s %s\n", _("Name:"), virDomainGetName(dom));

K
Karel Zak 已提交
4771
    if (virDomainGetUUIDString(dom, &uuid[0])==0)
4772
        vshPrint(ctl, "%-15s %s\n", _("UUID:"), uuid);
4773 4774

    if ((str = virDomainGetOSType(dom))) {
4775
        vshPrint(ctl, "%-15s %s\n", _("OS Type:"), str);
4776
        VIR_FREE(str);
4777 4778 4779
    }

    if (virDomainGetInfo(dom, &info) == 0) {
4780
        vshPrint(ctl, "%-15s %s\n", _("State:"),
E
Eric Blake 已提交
4781
                 _(vshDomainStateToString(info.state)));
4782

4783
        vshPrint(ctl, "%-15s %d\n", _("CPU(s):"), info.nrVirtCpu);
4784 4785

        if (info.cpuTime != 0) {
4786
            double cpuUsed = info.cpuTime;
4787

4788
            cpuUsed /= 1000000000.0;
4789

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

4793
        if (info.maxMem != UINT_MAX)
4794
            vshPrint(ctl, "%-15s %lu KiB\n", _("Max memory:"),
4795
                 info.maxMem);
4796
        else
4797
            vshPrint(ctl, "%-15s %s\n", _("Max memory:"),
4798 4799
                 _("no limit"));

4800
        vshPrint(ctl, "%-15s %lu KiB\n", _("Used memory:"),
4801 4802
                 info.memory);

K
Karel Zak 已提交
4803
    } else {
E
Eric Blake 已提交
4804
        ret = false;
K
Karel Zak 已提交
4805
    }
4806

4807 4808
    /* Check and display whether the domain is persistent or not */
    persistent = virDomainIsPersistent(dom);
4809 4810
    vshDebug(ctl, VSH_ERR_DEBUG, "Domain persistent flag value: %d\n",
             persistent);
4811 4812 4813 4814 4815 4816
    if (persistent < 0)
        vshPrint(ctl, "%-15s %s\n", _("Persistent:"), _("unknown"));
    else
        vshPrint(ctl, "%-15s %s\n", _("Persistent:"), persistent ? _("yes") : _("no"));

    /* Check and display whether the domain autostarts or not */
4817
    if (!virDomainGetAutostart(dom, &autostart)) {
4818
        vshPrint(ctl, "%-15s %s\n", _("Autostart:"),
4819 4820 4821
                 autostart ? _("enable") : _("disable") );
    }

4822 4823 4824 4825 4826 4827 4828
    has_managed_save = virDomainHasManagedSaveImage(dom, 0);
    if (has_managed_save < 0)
        vshPrint(ctl, "%-15s %s\n", _("Managed save:"), _("unknown"));
    else
        vshPrint(ctl, "%-15s %s\n", _("Managed save:"),
                 has_managed_save ? _("yes") : _("no"));

4829
    /* Security model and label information */
4830
    memset(&secmodel, 0, sizeof(secmodel));
4831
    if (virNodeGetSecurityModel(ctl->conn, &secmodel) == -1) {
4832 4833
        if (last_error->code != VIR_ERR_NO_SUPPORT) {
            virDomainFree(dom);
E
Eric Blake 已提交
4834
            return false;
4835 4836 4837
        } else {
            virFreeError(last_error);
            last_error = NULL;
4838
        }
4839 4840 4841 4842 4843 4844 4845
    } else {
        /* Only print something if a security model is active */
        if (secmodel.model[0] != '\0') {
            vshPrint(ctl, "%-15s %s\n", _("Security model:"), secmodel.model);
            vshPrint(ctl, "%-15s %s\n", _("Security DOI:"), secmodel.doi);

            /* Security labels are only valid for active domains */
4846
            if (VIR_ALLOC(seclabel) < 0) {
4847
                virDomainFree(dom);
E
Eric Blake 已提交
4848
                return false;
4849 4850 4851 4852 4853
            }

            if (virDomainGetSecurityLabel(dom, seclabel) == -1) {
                virDomainFree(dom);
                VIR_FREE(seclabel);
E
Eric Blake 已提交
4854
                return false;
4855
            } else {
4856
                if (seclabel->label[0] != '\0')
4857
                    vshPrint(ctl, "%-15s %s (%s)\n", _("Security label:"),
4858
                             seclabel->label, seclabel->enforcing ? "enforcing" : "permissive");
4859
            }
4860 4861

            VIR_FREE(seclabel);
4862 4863
        }
    }
4864
    virDomainFree(dom);
K
Karel Zak 已提交
4865 4866 4867
    return ret;
}

4868 4869 4870 4871
/*
 * "domjobinfo" command
 */
static const vshCmdInfo info_domjobinfo[] = {
4872 4873
    {"help", N_("domain job information")},
    {"desc", N_("Returns information about jobs running on a domain.")},
4874 4875 4876 4877
    {NULL, NULL}
};

static const vshCmdOptDef opts_domjobinfo[] = {
4878
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
4879 4880 4881 4882
    {NULL, 0, 0, NULL}
};


E
Eric Blake 已提交
4883
static bool
4884 4885 4886 4887
cmdDomjobinfo(vshControl *ctl, const vshCmd *cmd)
{
    virDomainJobInfo info;
    virDomainPtr dom;
E
Eric Blake 已提交
4888
    bool ret = true;
4889

4890
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
4891
        return false;
4892 4893

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
4894
        return false;
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

    if (virDomainGetJobInfo(dom, &info) == 0) {
        const char *unit;
        double val;

        vshPrint(ctl, "%-17s ", _("Job type:"));
        switch (info.type) {
        case VIR_DOMAIN_JOB_BOUNDED:
            vshPrint(ctl, "%-12s\n", _("Bounded"));
            break;

        case VIR_DOMAIN_JOB_UNBOUNDED:
            vshPrint(ctl, "%-12s\n", _("Unbounded"));
            break;

        case VIR_DOMAIN_JOB_NONE:
        default:
            vshPrint(ctl, "%-12s\n", _("None"));
            goto cleanup;
        }

        vshPrint(ctl, "%-17s %-12llu ms\n", _("Time elapsed:"), info.timeElapsed);
        if (info.type == VIR_DOMAIN_JOB_BOUNDED)
            vshPrint(ctl, "%-17s %-12llu ms\n", _("Time remaining:"), info.timeRemaining);
        if (info.dataTotal || info.dataRemaining || info.dataProcessed) {
            val = prettyCapacity(info.dataProcessed, &unit);
E
Eric Blake 已提交
4921
            vshPrint(ctl, "%-17s %-.3lf %s\n", _("Data processed:"), val, unit);
4922
            val = prettyCapacity(info.dataRemaining, &unit);
E
Eric Blake 已提交
4923
            vshPrint(ctl, "%-17s %-.3lf %s\n", _("Data remaining:"), val, unit);
4924
            val = prettyCapacity(info.dataTotal, &unit);
E
Eric Blake 已提交
4925
            vshPrint(ctl, "%-17s %-.3lf %s\n", _("Data total:"), val, unit);
4926 4927 4928
        }
        if (info.memTotal || info.memRemaining || info.memProcessed) {
            val = prettyCapacity(info.memProcessed, &unit);
E
Eric Blake 已提交
4929
            vshPrint(ctl, "%-17s %-.3lf %s\n", _("Memory processed:"), val, unit);
4930
            val = prettyCapacity(info.memRemaining, &unit);
E
Eric Blake 已提交
4931
            vshPrint(ctl, "%-17s %-.3lf %s\n", _("Memory remaining:"), val, unit);
4932
            val = prettyCapacity(info.memTotal, &unit);
E
Eric Blake 已提交
4933
            vshPrint(ctl, "%-17s %-.3lf %s\n", _("Memory total:"), val, unit);
4934 4935 4936
        }
        if (info.fileTotal || info.fileRemaining || info.fileProcessed) {
            val = prettyCapacity(info.fileProcessed, &unit);
E
Eric Blake 已提交
4937
            vshPrint(ctl, "%-17s %-.3lf %s\n", _("File processed:"), val, unit);
4938
            val = prettyCapacity(info.fileRemaining, &unit);
E
Eric Blake 已提交
4939
            vshPrint(ctl, "%-17s %-.3lf %s\n", _("File remaining:"), val, unit);
4940
            val = prettyCapacity(info.fileTotal, &unit);
E
Eric Blake 已提交
4941
            vshPrint(ctl, "%-17s %-.3lf %s\n", _("File total:"), val, unit);
4942 4943
        }
    } else {
E
Eric Blake 已提交
4944
        ret = false;
4945 4946 4947 4948 4949 4950
    }
cleanup:
    virDomainFree(dom);
    return ret;
}

4951 4952 4953 4954
/*
 * "domjobabort" command
 */
static const vshCmdInfo info_domjobabort[] = {
4955 4956
    {"help", N_("abort active domain job")},
    {"desc", N_("Aborts the currently running domain job")},
4957 4958 4959 4960
    {NULL, NULL}
};

static const vshCmdOptDef opts_domjobabort[] = {
4961
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
4962 4963 4964
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
4965
static bool
4966 4967 4968
cmdDomjobabort(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
E
Eric Blake 已提交
4969
    bool ret = true;
4970

4971
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
4972
        return false;
4973 4974

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
4975
        return false;
4976 4977

    if (virDomainAbortJob(dom) < 0)
E
Eric Blake 已提交
4978
        ret = false;
4979 4980 4981 4982 4983

    virDomainFree(dom);
    return ret;
}

4984 4985 4986
/*
 * "freecell" command
 */
4987
static const vshCmdInfo info_freecell[] = {
4988 4989
    {"help", N_("NUMA free memory")},
    {"desc", N_("display available free memory for the NUMA cell.")},
4990 4991 4992
    {NULL, NULL}
};

4993
static const vshCmdOptDef opts_freecell[] = {
4994
    {"cellno", VSH_OT_INT, 0, N_("NUMA cell number")},
4995
    {"all", VSH_OT_BOOL, 0, N_("show free memory for all NUMA cells")},
4996 4997 4998
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
4999
static bool
5000
cmdFreecell(vshControl *ctl, const vshCmd *cmd)
5001
{
W
Wen Congyang 已提交
5002
    bool func_ret = false;
5003
    int ret;
5004
    int cell = -1, cell_given;
5005
    unsigned long long memory;
5006 5007 5008 5009
    xmlNodePtr *nodes = NULL;
    unsigned long nodes_cnt;
    unsigned long *nodes_id = NULL;
    unsigned long long *nodes_free = NULL;
5010
    int all_given;
5011 5012 5013 5014
    int i;
    char *cap_xml = NULL;
    xmlDocPtr xml = NULL;
    xmlXPathContextPtr ctxt = NULL;
5015

5016

5017
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
5018
        return false;
5019

5020 5021 5022 5023
    if ( (cell_given = vshCommandOptInt(cmd, "cellno", &cell)) < 0) {
        vshError(ctl, "%s", _("cell number has to be a number"));
        goto cleanup;
    }
5024 5025 5026 5027 5028 5029 5030 5031 5032
    all_given = vshCommandOptBool(cmd, "all");

    if (all_given && cell_given) {
        vshError(ctl, "%s", _("--cellno and --all are mutually exclusive. "
                              "Please choose only one."));
        goto cleanup;
    }

    if (all_given) {
5033 5034 5035
        cap_xml = virConnectGetCapabilities(ctl->conn);
        if (!cap_xml) {
            vshError(ctl, "%s", _("unable to get node capabilities"));
5036 5037 5038
            goto cleanup;
        }

5039
        xml = virXMLParseStringCtxt(cap_xml, _("(capabilities)"), &ctxt);
5040 5041
        if (!xml) {
            vshError(ctl, "%s", _("unable to get node capabilities"));
5042 5043
            goto cleanup;
        }
5044 5045 5046 5047
        nodes_cnt = virXPathNodeSet("/capabilities/host/topology/cells/cell",
                                    ctxt, &nodes);

        if (nodes_cnt == -1) {
5048
            vshError(ctl, "%s", _("could not get information about "
5049
                                  "NUMA topology"));
5050 5051 5052
            goto cleanup;
        }

5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073
        nodes_free = vshCalloc(ctl, nodes_cnt, sizeof(*nodes_free));
        nodes_id = vshCalloc(ctl, nodes_cnt, sizeof(*nodes_id));

        for (i = 0; i < nodes_cnt; i++) {
            unsigned long id;
            char *val = virXMLPropString(nodes[i], "id");
            if (virStrToLong_ul(val, NULL, 10, &id)) {
                vshError(ctl, "%s", _("conversion from string failed"));
                VIR_FREE(val);
                goto cleanup;
            }
            VIR_FREE(val);
            nodes_id[i]=id;
            ret = virNodeGetCellsFreeMemory(ctl->conn, &(nodes_free[i]), id, 1);
            if (ret != 1) {
                vshError(ctl, _("failed to get free memory for NUMA node "
                                "number: %lu"), id);
                goto cleanup;
            }
        }

5074
        memory = 0;
5075
        for (cell = 0; cell < nodes_cnt; cell++) {
5076
            vshPrint(ctl, "%5lu: %10llu KiB\n", nodes_id[cell],
5077 5078
                    (nodes_free[cell]/1024));
            memory += nodes_free[cell];
5079 5080 5081
        }

        vshPrintExtra(ctl, "--------------------\n");
5082
        vshPrintExtra(ctl, "%5s: %10llu KiB\n", _("Total"), memory/1024);
5083
    } else {
5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094
        if (!cell_given) {
            memory = virNodeGetFreeMemory(ctl->conn);
            if (memory == 0)
                goto cleanup;
        } else {
            ret = virNodeGetCellsFreeMemory(ctl->conn, &memory, cell, 1);
            if (ret != 1)
                goto cleanup;
        }

        if (cell == -1)
5095
            vshPrint(ctl, "%s: %llu KiB\n", _("Total"), (memory/1024));
5096
        else
5097
            vshPrint(ctl, "%d: %llu KiB\n", cell, (memory/1024));
5098 5099
    }

E
Eric Blake 已提交
5100
    func_ret = true;
5101

5102
cleanup:
5103
    xmlXPathFreeContext(ctxt);
5104
    xmlFreeDoc(xml);
5105
    VIR_FREE(nodes);
5106 5107 5108
    VIR_FREE(nodes_free);
    VIR_FREE(nodes_id);
    VIR_FREE(cap_xml);
5109
    return func_ret;
5110 5111
}

E
Eric Blake 已提交
5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125
/*
 * "maxvcpus" command
 */
static const vshCmdInfo info_maxvcpus[] = {
    {"help", N_("connection vcpu maximum")},
    {"desc", N_("Show maximum number of virtual CPUs for guests on this connection.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_maxvcpus[] = {
    {"type", VSH_OT_STRING, 0, N_("domain type")},
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
5126
static bool
E
Eric Blake 已提交
5127 5128
cmdMaxvcpus(vshControl *ctl, const vshCmd *cmd)
{
5129
    const char *type = NULL;
E
Eric Blake 已提交
5130 5131
    int vcpus;

5132 5133
    if (vshCommandOptString(cmd, "type", &type) < 0) {
        vshError(ctl, "%s", _("Invalid type"));
E
Eric Blake 已提交
5134
        return false;
5135
    }
E
Eric Blake 已提交
5136 5137

    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
5138
        return false;
E
Eric Blake 已提交
5139 5140 5141

    vcpus = virConnectGetMaxVcpus(ctl->conn, type);
    if (vcpus < 0)
E
Eric Blake 已提交
5142
        return false;
E
Eric Blake 已提交
5143 5144
    vshPrint(ctl, "%d\n", vcpus);

E
Eric Blake 已提交
5145
    return true;
E
Eric Blake 已提交
5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159
}

/*
 * "vcpucount" command
 */
static const vshCmdInfo info_vcpucount[] = {
    {"help", N_("domain vcpu counts")},
    {"desc", N_("Returns the number of virtual CPUs used by the domain.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_vcpucount[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"maximum", VSH_OT_BOOL, 0, N_("get maximum cap on vcpus")},
5160
    {"active", VSH_OT_BOOL, 0, N_("get number of currently active vcpus")},
E
Eric Blake 已提交
5161
    {"live", VSH_OT_BOOL, 0, N_("get value from running domain")},
5162 5163 5164
    {"config", VSH_OT_BOOL, 0, N_("get value to be used on next boot")},
    {"current", VSH_OT_BOOL, 0,
     N_("get value according to current domain state")},
E
Eric Blake 已提交
5165 5166 5167
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
5168
static bool
E
Eric Blake 已提交
5169 5170 5171
cmdVcpucount(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
E
Eric Blake 已提交
5172
    bool ret = true;
5173 5174 5175 5176 5177
    bool maximum = vshCommandOptBool(cmd, "maximum");
    bool active = vshCommandOptBool(cmd, "active");
    bool config = vshCommandOptBool(cmd, "config");
    bool live = vshCommandOptBool(cmd, "live");
    bool current = vshCommandOptBool(cmd, "current");
5178
    bool all = maximum + active + current + config + live == 0;
E
Eric Blake 已提交
5179 5180
    int count;

5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195
    /* We want one of each pair of mutually exclusive options; that
     * is, use of flags requires exactly two options.  We reject the
     * use of more than 2 flags later on.  */
    if (maximum + active + current + config + live == 1) {
        if (maximum || active) {
            vshError(ctl,
                     _("when using --%s, one of --config, --live, or --current "
                       "must be specified"),
                     maximum ? "maximum" : "active");
        } else {
            vshError(ctl,
                     _("when using --%s, either --maximum or --active must be "
                       "specified"),
                     (current ? "current" : config ? "config" : "live"));
        }
E
Eric Blake 已提交
5196
        return false;
E
Eric Blake 已提交
5197
    }
5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210

    /* Backwards compatibility: prior to 0.9.4,
     * VIR_DOMAIN_AFFECT_CURRENT was unsupported, and --current meant
     * the opposite of --maximum.  Translate the old '--current
     * --live' into the new '--active --live', while treating the new
     * '--maximum --current' correctly rather than rejecting it as
     * '--maximum --active'.  */
    if (!maximum && !active && current) {
        current = false;
        active = true;
    }

    if (maximum && active) {
E
Eric Blake 已提交
5211
        vshError(ctl, "%s",
5212
                 _("--maximum and --active cannot both be specified"));
E
Eric Blake 已提交
5213
        return false;
E
Eric Blake 已提交
5214
    }
5215 5216 5217
    if (current + config + live > 1) {
        vshError(ctl, "%s",
                 _("--config, --live, and --current are mutually exclusive"));
E
Eric Blake 已提交
5218
        return false;
E
Eric Blake 已提交
5219 5220 5221
    }

    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
5222
        return false;
E
Eric Blake 已提交
5223 5224

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
5225
        return false;
E
Eric Blake 已提交
5226 5227

    /* In all cases, try the new API first; if it fails because we are
5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241
     * talking to an older client, generally we try a fallback API
     * before giving up.  --current requires the new API, since we
     * don't know whether the domain is running or inactive.  */
    if (current) {
        count = virDomainGetVcpusFlags(dom,
                                       maximum ? VIR_DOMAIN_VCPU_MAXIMUM : 0);
        if (count < 0) {
            virshReportError(ctl);
            ret = false;
        } else {
            vshPrint(ctl, "%d\n", count);
        }
    }

E
Eric Blake 已提交
5242 5243
    if (all || (maximum && config)) {
        count = virDomainGetVcpusFlags(dom, (VIR_DOMAIN_VCPU_MAXIMUM |
5244
                                             VIR_DOMAIN_AFFECT_CONFIG));
E
Eric Blake 已提交
5245 5246 5247 5248 5249 5250 5251 5252 5253
        if (count < 0 && (last_error->code == VIR_ERR_NO_SUPPORT
                          || last_error->code == VIR_ERR_INVALID_ARG)) {
            char *tmp;
            char *xml = virDomainGetXMLDesc(dom, VIR_DOMAIN_XML_INACTIVE);
            if (xml && (tmp = strstr(xml, "<vcpu"))) {
                tmp = strchr(tmp, '>');
                if (!tmp || virStrToLong_i(tmp + 1, &tmp, 10, &count) < 0)
                    count = -1;
            }
5254 5255
            virFreeError(last_error);
            last_error = NULL;
E
Eric Blake 已提交
5256 5257 5258 5259 5260
            VIR_FREE(xml);
        }

        if (count < 0) {
            virshReportError(ctl);
E
Eric Blake 已提交
5261
            ret = false;
E
Eric Blake 已提交
5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273
        } else if (all) {
            vshPrint(ctl, "%-12s %-12s %3d\n", _("maximum"), _("config"),
                     count);
        } else {
            vshPrint(ctl, "%d\n", count);
        }
        virFreeError(last_error);
        last_error = NULL;
    }

    if (all || (maximum && live)) {
        count = virDomainGetVcpusFlags(dom, (VIR_DOMAIN_VCPU_MAXIMUM |
5274
                                             VIR_DOMAIN_AFFECT_LIVE));
E
Eric Blake 已提交
5275 5276 5277 5278 5279 5280 5281
        if (count < 0 && (last_error->code == VIR_ERR_NO_SUPPORT
                          || last_error->code == VIR_ERR_INVALID_ARG)) {
            count = virDomainGetMaxVcpus(dom);
        }

        if (count < 0) {
            virshReportError(ctl);
E
Eric Blake 已提交
5282
            ret = false;
E
Eric Blake 已提交
5283 5284 5285 5286 5287 5288 5289 5290 5291 5292
        } else if (all) {
            vshPrint(ctl, "%-12s %-12s %3d\n", _("maximum"), _("live"),
                     count);
        } else {
            vshPrint(ctl, "%d\n", count);
        }
        virFreeError(last_error);
        last_error = NULL;
    }

5293
    if (all || (active && config)) {
5294
        count = virDomainGetVcpusFlags(dom, VIR_DOMAIN_AFFECT_CONFIG);
E
Eric Blake 已提交
5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318
        if (count < 0 && (last_error->code == VIR_ERR_NO_SUPPORT
                          || last_error->code == VIR_ERR_INVALID_ARG)) {
            char *tmp, *end;
            char *xml = virDomainGetXMLDesc(dom, VIR_DOMAIN_XML_INACTIVE);
            if (xml && (tmp = strstr(xml, "<vcpu"))) {
                end = strchr(tmp, '>');
                if (end) {
                    *end = '\0';
                    tmp = strstr(tmp, "current=");
                    if (!tmp)
                        tmp = end + 1;
                    else {
                        tmp += strlen("current=");
                        tmp += *tmp == '\'' || *tmp == '"';
                    }
                }
                if (!tmp || virStrToLong_i(tmp, &tmp, 10, &count) < 0)
                    count = -1;
            }
            VIR_FREE(xml);
        }

        if (count < 0) {
            virshReportError(ctl);
E
Eric Blake 已提交
5319
            ret = false;
E
Eric Blake 已提交
5320 5321 5322 5323 5324 5325 5326 5327 5328 5329
        } else if (all) {
            vshPrint(ctl, "%-12s %-12s %3d\n", _("current"), _("config"),
                     count);
        } else {
            vshPrint(ctl, "%d\n", count);
        }
        virFreeError(last_error);
        last_error = NULL;
    }

5330
    if (all || (active && live)) {
5331
        count = virDomainGetVcpusFlags(dom, VIR_DOMAIN_AFFECT_LIVE);
E
Eric Blake 已提交
5332 5333 5334 5335 5336 5337 5338 5339 5340
        if (count < 0 && (last_error->code == VIR_ERR_NO_SUPPORT
                          || last_error->code == VIR_ERR_INVALID_ARG)) {
            virDomainInfo info;
            if (virDomainGetInfo(dom, &info) == 0)
                count = info.nrVirtCpu;
        }

        if (count < 0) {
            virshReportError(ctl);
E
Eric Blake 已提交
5341
            ret = false;
E
Eric Blake 已提交
5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355
        } else if (all) {
            vshPrint(ctl, "%-12s %-12s %3d\n", _("current"), _("live"),
                     count);
        } else {
            vshPrint(ctl, "%d\n", count);
        }
        virFreeError(last_error);
        last_error = NULL;
    }

    virDomainFree(dom);
    return ret;
}

5356 5357 5358
/*
 * "vcpuinfo" command
 */
5359
static const vshCmdInfo info_vcpuinfo[] = {
E
Eric Blake 已提交
5360
    {"help", N_("detailed domain vcpu information")},
5361
    {"desc", N_("Returns basic information about the domain virtual CPUs.")},
5362 5363 5364
    {NULL, NULL}
};

5365
static const vshCmdOptDef opts_vcpuinfo[] = {
5366
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
5367 5368 5369
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
5370
static bool
5371
cmdVcpuinfo(vshControl *ctl, const vshCmd *cmd)
5372 5373 5374 5375 5376
{
    virDomainInfo info;
    virDomainPtr dom;
    virNodeInfo nodeinfo;
    virVcpuInfoPtr cpuinfo;
5377 5378
    unsigned char *cpumaps;
    int ncpus, maxcpu;
5379
    size_t cpumaplen;
E
Eric Blake 已提交
5380
    bool ret = true;
5381
    int n, m;
5382

5383
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
5384
        return false;
5385

J
Jim Meyering 已提交
5386
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
5387
        return false;
5388 5389 5390

    if (virNodeGetInfo(ctl->conn, &nodeinfo) != 0) {
        virDomainFree(dom);
E
Eric Blake 已提交
5391
        return false;
5392 5393 5394 5395
    }

    if (virDomainGetInfo(dom, &info) != 0) {
        virDomainFree(dom);
E
Eric Blake 已提交
5396
        return false;
5397 5398
    }

5399
    cpuinfo = vshMalloc(ctl, sizeof(virVcpuInfo)*info.nrVirtCpu);
5400 5401 5402
    maxcpu = VIR_NODEINFO_MAXCPUS(nodeinfo);
    cpumaplen = VIR_CPU_MAPLEN(maxcpu);
    cpumaps = vshMalloc(ctl, info.nrVirtCpu * cpumaplen);
5403

5404 5405
    if ((ncpus = virDomainGetVcpus(dom,
                                   cpuinfo, info.nrVirtCpu,
5406
                                   cpumaps, cpumaplen)) >= 0) {
5407 5408 5409 5410
        for (n = 0 ; n < ncpus ; n++) {
            vshPrint(ctl, "%-15s %d\n", _("VCPU:"), n);
            vshPrint(ctl, "%-15s %d\n", _("CPU:"), cpuinfo[n].cpu);
            vshPrint(ctl, "%-15s %s\n", _("State:"),
E
Eric Blake 已提交
5411
                     _(vshDomainVcpuStateToString(cpuinfo[n].state)));
5412 5413 5414 5415 5416 5417 5418 5419
            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:"));
5420 5421
            for (m = 0; m < maxcpu; m++) {
                vshPrint(ctl, "%c", VIR_CPU_USABLE(cpumaps, cpumaplen, n, m) ? 'y' : '-');
5422 5423 5424 5425 5426 5427
            }
            vshPrint(ctl, "\n");
            if (n < (ncpus - 1)) {
                vshPrint(ctl, "\n");
            }
        }
5428
    } else {
5429
        if (info.state == VIR_DOMAIN_SHUTOFF &&
E
Eric Blake 已提交
5430
            (ncpus = virDomainGetVcpuPinInfo(dom, info.nrVirtCpu,
5431 5432 5433
                                             cpumaps, cpumaplen,
                                             VIR_DOMAIN_AFFECT_CONFIG)) >= 0) {

E
Eric Blake 已提交
5434
            /* fallback plan to use virDomainGetVcpuPinInfo */
5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452

            for (n = 0; n < ncpus; n++) {
                vshPrint(ctl, "%-15s %d\n", _("VCPU:"), n);
                vshPrint(ctl, "%-15s %s\n", _("CPU:"), _("N/A"));
                vshPrint(ctl, "%-15s %s\n", _("State:"), _("N/A"));
                vshPrint(ctl, "%-15s %s\n", _("CPU time"), _("N/A"));
                vshPrint(ctl, "%-15s ", _("CPU Affinity:"));
                for (m = 0; m < maxcpu; m++) {
                    vshPrint(ctl, "%c",
                             VIR_CPU_USABLE(cpumaps, cpumaplen, n, m) ? 'y' : '-');
                }
                vshPrint(ctl, "\n");
                if (n < (ncpus - 1)) {
                    vshPrint(ctl, "\n");
                }
            }
        } else {
            ret = false;
5453
        }
5454 5455
    }

5456
    VIR_FREE(cpumaps);
5457
    VIR_FREE(cpuinfo);
5458 5459 5460 5461 5462 5463 5464
    virDomainFree(dom);
    return ret;
}

/*
 * "vcpupin" command
 */
5465
static const vshCmdInfo info_vcpupin[] = {
5466
    {"help", N_("control or query domain vcpu affinity")},
5467
    {"desc", N_("Pin domain VCPUs to host physical CPUs.")},
5468 5469 5470
    {NULL, NULL}
};

5471
static const vshCmdOptDef opts_vcpupin[] = {
5472
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
5473 5474 5475
    {"vcpu", VSH_OT_INT, 0, N_("vcpu number")},
    {"cpulist", VSH_OT_DATA, VSH_OFLAG_EMPTY_OK,
     N_("host cpu number(s) to set, or omit option to query")},
5476 5477 5478
    {"config", VSH_OT_BOOL, 0, N_("affect next boot")},
    {"live", VSH_OT_BOOL, 0, N_("affect running domain")},
    {"current", VSH_OT_BOOL, 0, N_("affect current domain")},
5479 5480 5481
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
5482
static bool
E
Eric Blake 已提交
5483
cmdVcpuPin(vshControl *ctl, const vshCmd *cmd)
5484 5485 5486 5487
{
    virDomainInfo info;
    virDomainPtr dom;
    virNodeInfo nodeinfo;
5488
    int vcpu = -1;
5489
    const char *cpulist = NULL;
E
Eric Blake 已提交
5490
    bool ret = true;
5491 5492
    unsigned char *cpumap = NULL;
    unsigned char *cpumaps = NULL;
E
Eric Blake 已提交
5493
    size_t cpumaplen;
5494 5495
    bool bit, lastbit, isInvert;
    int i, cpu, lastcpu, maxcpu, ncpus;
5496
    bool unuse = false;
5497
    const char *cur;
5498 5499 5500
    bool config = vshCommandOptBool(cmd, "config");
    bool live = vshCommandOptBool(cmd, "live");
    bool current = vshCommandOptBool(cmd, "current");
5501
    bool query = false; /* Query mode if no cpulist */
E
Eric Blake 已提交
5502
    unsigned int flags = 0;
5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518

    if (current) {
        if (live || config) {
            vshError(ctl, "%s", _("--current must be specified exclusively"));
            return false;
        }
        flags = VIR_DOMAIN_AFFECT_CURRENT;
    } else {
        if (config)
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
        if (live)
            flags |= VIR_DOMAIN_AFFECT_LIVE;
        /* neither option is specified */
        if (!live && !config)
            flags = -1;
    }
5519

5520
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
5521
        return false;
5522

J
Jim Meyering 已提交
5523
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
5524
        return false;
5525

5526 5527
    if (vshCommandOptString(cmd, "cpulist", &cpulist) < 0) {
        vshError(ctl, "%s", _("vcpupin: Missing cpulist."));
5528
        virDomainFree(dom);
E
Eric Blake 已提交
5529
        return false;
5530
    }
5531
    query = !cpulist;
5532

5533 5534 5535 5536
    /* In query mode, "vcpu" is optional */
    if (vshCommandOptInt(cmd, "vcpu", &vcpu) < !query) {
        vshError(ctl, "%s",
                 _("vcpupin: Invalid or missing vCPU number."));
5537
        virDomainFree(dom);
E
Eric Blake 已提交
5538
        return false;
5539
    }
5540

5541 5542
    if (virNodeGetInfo(ctl->conn, &nodeinfo) != 0) {
        virDomainFree(dom);
E
Eric Blake 已提交
5543
        return false;
5544 5545 5546
    }

    if (virDomainGetInfo(dom, &info) != 0) {
5547
        vshError(ctl, "%s", _("vcpupin: failed to get domain information."));
5548
        virDomainFree(dom);
E
Eric Blake 已提交
5549
        return false;
5550 5551 5552
    }

    if (vcpu >= info.nrVirtCpu) {
5553
        vshError(ctl, "%s", _("vcpupin: Invalid vCPU number."));
5554
        virDomainFree(dom);
E
Eric Blake 已提交
5555
        return false;
5556 5557
    }

5558 5559
    maxcpu = VIR_NODEINFO_MAXCPUS(nodeinfo);
    cpumaplen = VIR_CPU_MAPLEN(maxcpu);
5560

5561 5562 5563 5564 5565 5566 5567 5568
    /* Query mode: show CPU affinity information then exit.*/
    if (query) {
        /* When query mode and neither "live", "config" nor "current"
         * is specified, set VIR_DOMAIN_AFFECT_CURRENT as flags */
        if (flags == -1)
            flags = VIR_DOMAIN_AFFECT_CURRENT;

        cpumaps = vshMalloc(ctl, info.nrVirtCpu * cpumaplen);
E
Eric Blake 已提交
5569
        if ((ncpus = virDomainGetVcpuPinInfo(dom, info.nrVirtCpu,
5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613
                                             cpumaps, cpumaplen, flags)) >= 0) {

            vshPrint(ctl, "%s %s\n", _("VCPU:"), _("CPU Affinity"));
            vshPrint(ctl, "----------------------------------\n");
            for (i = 0; i < ncpus; i++) {

               if (vcpu != -1 && i != vcpu)
                   continue;

               bit = lastbit = isInvert = false;
               lastcpu = -1;

               vshPrint(ctl, "%4d: ", i);
               for (cpu = 0; cpu < maxcpu; cpu++) {

                   bit = VIR_CPU_USABLE(cpumaps, cpumaplen, i, cpu);

                   isInvert = (bit ^ lastbit);
                   if (bit && isInvert) {
                       if (lastcpu == -1)
                           vshPrint(ctl, "%d", cpu);
                       else
                           vshPrint(ctl, ",%d", cpu);
                       lastcpu = cpu;
                   }
                   if (!bit && isInvert && lastcpu != cpu - 1)
                       vshPrint(ctl, "-%d", cpu - 1);
                   lastbit = bit;
               }
               if (bit && !isInvert) {
                  vshPrint(ctl, "-%d", maxcpu - 1);
               }
               vshPrint(ctl, "\n");
            }

        } else {
            ret = false;
        }
        VIR_FREE(cpumaps);
        goto cleanup;
    }

    /* Pin mode: pinning specified vcpu to specified physical cpus*/

5614
    cpumap = vshCalloc(ctl, cpumaplen, sizeof(cpumap));
5615 5616
    /* Parse cpulist */
    cur = cpulist;
5617
    if (*cur == 0) {
5618
        goto parse_error;
5619 5620 5621
    } else if (*cur == 'r') {
        for (cpu = 0; cpu < maxcpu; cpu++)
            VIR_USE_CPU(cpumap, cpu);
5622
        cur = "";
5623
    }
5624 5625 5626 5627 5628 5629 5630

    while (*cur != 0) {

        /* the char '^' denotes exclusive */
        if (*cur == '^') {
            cur++;
            unuse = true;
5631 5632
        }

5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644
        /* parse physical CPU number */
        if (!c_isdigit(*cur))
            goto parse_error;
        cpu  = virParseNumber(&cur);
        if (cpu < 0) {
            goto parse_error;
        }
        if (cpu >= maxcpu) {
            vshError(ctl, _("Physical CPU %d doesn't exist."), cpu);
            goto parse_error;
        }
        virSkipSpaces(&cur);
5645

E
Eric Blake 已提交
5646
        if (*cur == ',' || *cur == 0) {
5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672
            if (unuse) {
                VIR_UNUSE_CPU(cpumap, cpu);
            } else {
                VIR_USE_CPU(cpumap, cpu);
            }
        } else if (*cur == '-') {
            /* the char '-' denotes range */
            if (unuse) {
                goto parse_error;
            }
            cur++;
            virSkipSpaces(&cur);
            /* parse the end of range */
            lastcpu = virParseNumber(&cur);
            if (lastcpu < cpu) {
                goto parse_error;
            }
            if (lastcpu >= maxcpu) {
                vshError(ctl, _("Physical CPU %d doesn't exist."), maxcpu);
                goto parse_error;
            }
            for (i = cpu; i <= lastcpu; i++) {
                VIR_USE_CPU(cpumap, i);
            }
            virSkipSpaces(&cur);
        }
5673

5674 5675 5676 5677 5678 5679
        if (*cur == ',') {
            cur++;
            virSkipSpaces(&cur);
            unuse = false;
        } else if (*cur == 0) {
            break;
5680
        } else {
5681
            goto parse_error;
5682
        }
5683
    }
5684

5685 5686 5687 5688 5689 5690 5691 5692
    if (flags == -1) {
        if (virDomainPinVcpu(dom, vcpu, cpumap, cpumaplen) != 0) {
            ret = false;
        }
    } else {
        if (virDomainPinVcpuFlags(dom, vcpu, cpumap, cpumaplen, flags) != 0) {
            ret = false;
        }
5693 5694
    }

5695
cleanup:
5696
    VIR_FREE(cpumap);
5697 5698
    virDomainFree(dom);
    return ret;
5699 5700 5701 5702 5703

parse_error:
    vshError(ctl, "%s", _("cpulist: Invalid format."));
    ret = false;
    goto cleanup;
5704 5705
}

5706 5707 5708
/*
 * "setvcpus" command
 */
5709
static const vshCmdInfo info_setvcpus[] = {
5710 5711
    {"help", N_("change number of virtual CPUs")},
    {"desc", N_("Change the number of virtual CPUs in the guest domain.")},
5712 5713 5714
    {NULL, NULL}
};

5715
static const vshCmdOptDef opts_setvcpus[] = {
5716
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
5717
    {"count", VSH_OT_INT, VSH_OFLAG_REQ, N_("number of virtual CPUs")},
E
Eric Blake 已提交
5718 5719 5720
    {"maximum", VSH_OT_BOOL, 0, N_("set maximum limit on next boot")},
    {"config", VSH_OT_BOOL, 0, N_("affect next boot")},
    {"live", VSH_OT_BOOL, 0, N_("affect running domain")},
5721
    {"current", VSH_OT_BOOL, 0, N_("affect current domain")},
5722 5723 5724
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
5725
static bool
5726
cmdSetvcpus(vshControl *ctl, const vshCmd *cmd)
5727 5728
{
    virDomainPtr dom;
5729
    int count = 0;
E
Eric Blake 已提交
5730
    bool ret = true;
5731 5732 5733 5734
    bool maximum = vshCommandOptBool(cmd, "maximum");
    bool config = vshCommandOptBool(cmd, "config");
    bool live = vshCommandOptBool(cmd, "live");
    bool current = vshCommandOptBool(cmd, "current");
E
Eric Blake 已提交
5735
    unsigned int flags = 0;
5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751

    if (current) {
        if (live || config) {
            vshError(ctl, "%s", _("--current must be specified exclusively"));
            return false;
        }
        flags = VIR_DOMAIN_AFFECT_CURRENT;
    } else {
        if (config)
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
        if (live)
            flags |= VIR_DOMAIN_AFFECT_LIVE;
        /* neither option is specified */
        if (!live && !config && !maximum)
            flags = -1;
    }
5752

5753
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
5754
        return false;
5755

J
Jim Meyering 已提交
5756
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
5757
        return false;
5758

5759
    if (vshCommandOptInt(cmd, "count", &count) < 0 || count <= 0) {
5760 5761 5762
        vshError(ctl, "%s", _("Invalid number of virtual CPUs"));
        goto cleanup;
    }
5763

5764
    if (flags == -1) {
E
Eric Blake 已提交
5765
        if (virDomainSetVcpus(dom, count) != 0) {
E
Eric Blake 已提交
5766
            ret = false;
E
Eric Blake 已提交
5767 5768
        }
    } else {
5769 5770 5771
        /* If the --maximum flag was given, we need to ensure only the
           --config flag is in effect as well */
        if (maximum) {
5772
            vshDebug(ctl, VSH_ERR_DEBUG, "--maximum flag was given\n");
5773

5774 5775
            flags |= VIR_DOMAIN_VCPU_MAXIMUM;

5776 5777 5778 5779 5780 5781 5782 5783
            /* If neither the --config nor --live flags were given, OR
               if just the --live flag was given, we need to error out
               warning the user that the --maximum flag can only be used
               with the --config flag */
            if (live || !config) {

                /* Warn the user about the invalid flag combination */
                vshError(ctl, _("--maximum must be used with --config only"));
E
Eric Blake 已提交
5784
                ret = false;
5785 5786 5787 5788 5789
                goto cleanup;
            }
        }

        /* Apply the virtual cpu changes */
E
Eric Blake 已提交
5790
        if (virDomainSetVcpusFlags(dom, count, flags) < 0) {
E
Eric Blake 已提交
5791
            ret = false;
E
Eric Blake 已提交
5792
        }
5793 5794
    }

5795
  cleanup:
5796 5797 5798 5799
    virDomainFree(dom);
    return ret;
}

5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824
/*
 * "cpu-stats" command
 */
static const vshCmdInfo info_cpu_stats[] = {
    {"help", N_("show domain cpu statistics")},
    {"desc",
     N_("Display per-CPU and total statistics about the domain's CPUs")},
    {NULL, NULL},
};

static const vshCmdOptDef opts_cpu_stats[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"total", VSH_OT_BOOL, 0, N_("Show total statistics only")},
    {"start", VSH_OT_INT, 0, N_("Show statistics from this CPU")},
    {"count", VSH_OT_INT, 0, N_("Number of shown CPUs at most")},
    {NULL, 0, 0, NULL},
};

static bool
cmdCPUStats(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    virTypedParameterPtr params = NULL;
    int i, j, pos, max_id, cpu = -1, show_count = -1, nparams;
    bool show_total = false, show_per_cpu = false;
5825
    unsigned int flags = 0;
5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852

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

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
        return false;

    show_total = vshCommandOptBool(cmd, "total");
    if (vshCommandOptInt(cmd, "start", &cpu) > 0)
        show_per_cpu = true;
    if (vshCommandOptInt(cmd, "count", &show_count) > 0)
        show_per_cpu = true;

    /* default show per_cpu and total */
    if (!show_total && !show_per_cpu) {
        show_total = true;
        show_per_cpu = true;
    }

    if (!show_per_cpu) /* show total stats only */
        goto do_show_total;

    /* check cpu, show_count, and ignore wrong argument */
    if (cpu < 0)
        cpu = 0;

    /* get number of cpus on the node */
5853
    if ((max_id = virDomainGetCPUStats(dom, NULL, 0, 0, 0, flags)) < 0)
5854 5855 5856 5857 5858
        goto failed_stats;
    if (show_count < 0 || show_count > max_id)
        show_count = max_id;

    /* get percpu information */
5859
    if ((nparams = virDomainGetCPUStats(dom, NULL, 0, 0, 1, flags)) < 0)
5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872
        goto failed_stats;

    if (!nparams) {
        vshPrint(ctl, "%s", _("No per-CPU stats available"));
        goto do_show_total;
    }

    if (VIR_ALLOC_N(params, nparams * MIN(show_count, 128)) < 0)
        goto failed_params;

    while (show_count) {
        int ncpus = MIN(show_count, 128);

5873
        if (virDomainGetCPUStats(dom, params, nparams, cpu, ncpus, flags) < 0)
5874 5875 5876 5877 5878 5879 5880 5881 5882
            goto failed_stats;

        for (i = 0; i < ncpus; i++) {
            if (params[i * nparams].type == 0) /* this cpu is not in the map */
                continue;
            vshPrint(ctl, "CPU%d:\n", cpu + i);

            for (j = 0; j < nparams; j++) {
                pos = i * nparams + j;
E
Eric Blake 已提交
5883
                vshPrint(ctl, "\t%-12s ", params[pos].field);
5884 5885
                if ((STREQ(params[pos].field, VIR_DOMAIN_CPU_STATS_CPUTIME) ||
                     STREQ(params[pos].field, VIR_DOMAIN_CPU_STATS_VCPUTIME)) &&
5886
                    params[j].type == VIR_TYPED_PARAM_ULLONG) {
E
Eric Blake 已提交
5887
                    vshPrint(ctl, "%9lld.%09lld seconds\n",
5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907
                             params[pos].value.ul / 1000000000,
                             params[pos].value.ul % 1000000000);
                } else {
                    const char *s = vshGetTypedParamValue(ctl, &params[pos]);
                    vshPrint(ctl, _("%s\n"), s);
                    VIR_FREE(s);
                }
            }
        }
        cpu += ncpus;
        show_count -= ncpus;
        virTypedParameterArrayClear(params, nparams * ncpus);
    }
    VIR_FREE(params);

do_show_total:
    if (!show_total)
        goto cleanup;

    /* get supported num of parameter for total statistics */
5908
    if ((nparams = virDomainGetCPUStats(dom, NULL, 0, -1, 1, flags)) < 0)
5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919
        goto failed_stats;

    if (!nparams) {
        vshPrint(ctl, "%s", _("No total stats available"));
        goto cleanup;
    }

    if (VIR_ALLOC_N(params, nparams))
        goto failed_params;

    /* passing start_cpu == -1 gives us domain's total status */
5920
    if ((nparams = virDomainGetCPUStats(dom, params, nparams, -1, 1, flags)) < 0)
5921 5922 5923 5924
        goto failed_stats;

    vshPrint(ctl, _("Total:\n"));
    for (i = 0; i < nparams; i++) {
E
Eric Blake 已提交
5925 5926 5927 5928
        vshPrint(ctl, "\t%-12s ", params[i].field);
        if ((STREQ(params[i].field, VIR_DOMAIN_CPU_STATS_CPUTIME) ||
             STREQ(params[i].field, VIR_DOMAIN_CPU_STATS_USERTIME) ||
             STREQ(params[i].field, VIR_DOMAIN_CPU_STATS_SYSTEMTIME)) &&
5929
            params[i].type == VIR_TYPED_PARAM_ULLONG) {
E
Eric Blake 已提交
5930
            vshPrint(ctl, "%9lld.%09lld seconds\n",
5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957
                     params[i].value.ul / 1000000000,
                     params[i].value.ul % 1000000000);
        } else {
            char *s = vshGetTypedParamValue(ctl, &params[i]);
            vshPrint(ctl, "%s\n", s);
            VIR_FREE(s);
        }
    }
    virTypedParameterArrayClear(params, nparams);
    VIR_FREE(params);

cleanup:
    virDomainFree(dom);
    return true;

failed_params:
    virReportOOMError();
    virDomainFree(dom);
    return false;

failed_stats:
    vshError(ctl, _("Failed to virDomainGetCPUStats()\n"));
    VIR_FREE(params);
    virDomainFree(dom);
    return false;
}

5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991
/*
 * "inject-nmi" command
 */
static const vshCmdInfo info_inject_nmi[] = {
    {"help", N_("Inject NMI to the guest")},
    {"desc", N_("Inject NMI to the guest domain.")},
    {NULL, NULL}
};

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


static bool
cmdInjectNMI(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    int ret = true;

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

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
        return false;

    if (virDomainInjectNMI(dom, 0) < 0)
            ret = false;

    virDomainFree(dom);
    return ret;
}

5992 5993 5994 5995 5996
/*
 * "send-key" command
 */
static const vshCmdInfo info_send_key[] = {
    {"help", N_("Send keycodes to the guest")},
5997
    {"desc", N_("Send keycodes (integers or symbolic names) to the guest")},
5998 5999 6000 6001 6002
    {NULL, NULL}
};

static const vshCmdOptDef opts_send_key[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
6003 6004
    {"codeset", VSH_OT_STRING, VSH_OFLAG_REQ_OPT,
     N_("the codeset of keycodes, default:linux")},
6005
    {"holdtime", VSH_OT_INT, VSH_OFLAG_REQ_OPT,
A
Alex Jia 已提交
6006
     N_("the time (in milliseconds) how long the keys will be held")},
6007 6008 6009 6010
    {"keycode", VSH_OT_ARGV, VSH_OFLAG_REQ, N_("the key code")},
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
6011 6012
static int
get_integer_keycode(const char *key_name)
6013
{
E
Eric Blake 已提交
6014
    unsigned int val;
6015

E
Eric Blake 已提交
6016 6017
    if (virStrToLong_ui(key_name, NULL, 0, &val) < 0 || val > 0xffff || !val)
        return -1;
6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076
    return val;
}

static bool
cmdSendKey(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    int ret = false;
    const char *codeset_option;
    int codeset;
    int holdtime;
    int count = 0;
    const vshCmdOpt *opt = NULL;
    int keycode;
    unsigned int keycodes[VIR_DOMAIN_SEND_KEY_MAX_KEYS];

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

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
        return false;

    if (vshCommandOptString(cmd, "codeset", &codeset_option) <= 0)
        codeset_option = "linux";

    if (vshCommandOptInt(cmd, "holdtime", &holdtime) <= 0)
        holdtime = 0;

    codeset = virKeycodeSetTypeFromString(codeset_option);
    if ((int)codeset < 0) {
        vshError(ctl, _("unknown codeset: '%s'"), codeset_option);
        goto cleanup;
    }

    while ((opt = vshCommandOptArgv(cmd, opt))) {
        if (count == VIR_DOMAIN_SEND_KEY_MAX_KEYS) {
            vshError(ctl, _("too many keycodes"));
            goto cleanup;
        }

        if ((keycode = get_integer_keycode(opt->data)) <= 0) {
            if ((keycode = virKeycodeValueFromString(codeset, opt->data)) <= 0) {
                vshError(ctl, _("invalid keycode: '%s'"), opt->data);
                goto cleanup;
            }
        }

        keycodes[count] = keycode;
        count++;
    }

    if (!(virDomainSendKey(dom, codeset, holdtime, keycodes, count, 0) < 0))
        ret = true;

cleanup:
    virDomainFree(dom);
    return ret;
}

6077
/*
E
Eric Blake 已提交
6078
 * "setmem" command
6079
 */
6080
static const vshCmdInfo info_setmem[] = {
6081 6082
    {"help", N_("change memory allocation")},
    {"desc", N_("Change the current memory allocation in the guest domain.")},
6083 6084 6085
    {NULL, NULL}
};

6086
static const vshCmdOptDef opts_setmem[] = {
6087
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
E
Eric Blake 已提交
6088 6089 6090
    {"kilobytes", VSH_OT_ALIAS, 0, "size"},
    {"size", VSH_OT_INT, VSH_OFLAG_REQ,
     N_("new memory size, as scaled integer (default KiB)")},
6091 6092
    {"config", VSH_OT_BOOL, 0, N_("affect next boot")},
    {"live", VSH_OT_BOOL, 0, N_("affect running domain")},
6093
    {"current", VSH_OT_BOOL, 0, N_("affect current domain")},
6094 6095 6096
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
6097
static bool
6098
cmdSetmem(vshControl *ctl, const vshCmd *cmd)
6099 6100
{
    virDomainPtr dom;
E
Eric Blake 已提交
6101 6102 6103
    unsigned long long bytes = 0;
    unsigned long long max;
    unsigned long kibibytes = 0;
E
Eric Blake 已提交
6104
    bool ret = true;
6105 6106 6107
    bool config = vshCommandOptBool(cmd, "config");
    bool live = vshCommandOptBool(cmd, "live");
    bool current = vshCommandOptBool(cmd, "current");
E
Eric Blake 已提交
6108
    unsigned int flags = 0;
6109

6110 6111 6112
    if (current) {
        if (live || config) {
            vshError(ctl, "%s", _("--current must be specified exclusively"));
E
Eric Blake 已提交
6113
            return false;
6114
        }
6115
        flags = VIR_DOMAIN_AFFECT_CURRENT;
6116 6117
    } else {
        if (config)
6118
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
6119
        if (live)
6120
            flags |= VIR_DOMAIN_AFFECT_LIVE;
6121 6122 6123
        /* neither option is specified */
        if (!live && !config)
            flags = -1;
6124
    }
6125

6126
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
6127
        return false;
6128

J
Jim Meyering 已提交
6129
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
6130
        return false;
6131

E
Eric Blake 已提交
6132 6133 6134 6135 6136 6137 6138
    /* The API expects 'unsigned long' KiB, so depending on whether we
     * are 32-bit or 64-bit determines the maximum we can use.  */
    if (sizeof(kibibytes) < sizeof(max))
        max = 1024ull * ULONG_MAX;
    else
        max = ULONG_MAX;
    if (vshCommandOptScaledInt(cmd, "size", &bytes, 1024, max) < 0) {
6139
        vshError(ctl, "%s", _("memory size has to be a number"));
6140
        virDomainFree(dom);
E
Eric Blake 已提交
6141
        return false;
6142
    }
E
Eric Blake 已提交
6143
    kibibytes = VIR_DIV_UP(bytes, 1024);
6144

6145
    if (flags == -1) {
E
Eric Blake 已提交
6146
        if (virDomainSetMemory(dom, kibibytes) != 0) {
E
Eric Blake 已提交
6147
            ret = false;
6148 6149
        }
    } else {
E
Eric Blake 已提交
6150
        if (virDomainSetMemoryFlags(dom, kibibytes, flags) < 0) {
E
Eric Blake 已提交
6151
            ret = false;
6152
        }
6153 6154 6155 6156 6157 6158 6159 6160 6161
    }

    virDomainFree(dom);
    return ret;
}

/*
 * "setmaxmem" command
 */
6162
static const vshCmdInfo info_setmaxmem[] = {
6163 6164
    {"help", N_("change maximum memory limit")},
    {"desc", N_("Change the maximum memory allocation limit in the guest domain.")},
6165 6166 6167
    {NULL, NULL}
};

6168
static const vshCmdOptDef opts_setmaxmem[] = {
6169
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
E
Eric Blake 已提交
6170 6171 6172
    {"kilobytes", VSH_OT_ALIAS, 0, "size"},
    {"size", VSH_OT_INT, VSH_OFLAG_REQ,
     N_("new maximum memory size, as scaled integer (default KiB)")},
6173 6174 6175
    {"config", VSH_OT_BOOL, 0, N_("affect next boot")},
    {"live", VSH_OT_BOOL, 0, N_("affect running domain")},
    {"current", VSH_OT_BOOL, 0, N_("affect current domain")},
6176 6177 6178
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
6179
static bool
6180
cmdSetmaxmem(vshControl *ctl, const vshCmd *cmd)
6181 6182
{
    virDomainPtr dom;
E
Eric Blake 已提交
6183 6184 6185
    unsigned long long bytes = 0;
    unsigned long long max;
    unsigned long kibibytes = 0;
E
Eric Blake 已提交
6186
    bool ret = true;
6187 6188 6189
    bool config = vshCommandOptBool(cmd, "config");
    bool live = vshCommandOptBool(cmd, "live");
    bool current = vshCommandOptBool(cmd, "current");
E
Eric Blake 已提交
6190
    unsigned int flags = VIR_DOMAIN_MEM_MAXIMUM;
6191 6192 6193 6194

    if (current) {
        if (live || config) {
            vshError(ctl, "%s", _("--current must be specified exclusively"));
E
Eric Blake 已提交
6195
            return false;
6196 6197 6198
        }
    } else {
        if (config)
6199
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
6200
        if (live)
6201
            flags |= VIR_DOMAIN_AFFECT_LIVE;
6202 6203 6204 6205
        /* neither option is specified */
        if (!live && !config)
            flags = -1;
    }
6206

6207
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
6208
        return false;
6209

J
Jim Meyering 已提交
6210
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
6211
        return false;
6212

E
Eric Blake 已提交
6213 6214 6215 6216 6217 6218 6219
    /* The API expects 'unsigned long' KiB, so depending on whether we
     * are 32-bit or 64-bit determines the maximum we can use.  */
    if (sizeof(kibibytes) < sizeof(max))
        max = 1024ull * ULONG_MAX;
    else
        max = ULONG_MAX;
    if (vshCommandOptScaledInt(cmd, "size", &bytes, 1024, max) < 0) {
6220
        vshError(ctl, "%s", _("memory size has to be a number"));
6221
        virDomainFree(dom);
E
Eric Blake 已提交
6222
        return false;
6223
    }
E
Eric Blake 已提交
6224
    kibibytes = VIR_DIV_UP(bytes, 1024);
6225

6226
    if (flags == -1) {
E
Eric Blake 已提交
6227
        if (virDomainSetMaxMemory(dom, kibibytes) != 0) {
6228
            vshError(ctl, "%s", _("Unable to change MaxMemorySize"));
E
Eric Blake 已提交
6229
            ret = false;
6230 6231
        }
    } else {
E
Eric Blake 已提交
6232
        if (virDomainSetMemoryFlags(dom, kibibytes, flags) < 0) {
6233
            vshError(ctl, "%s", _("Unable to change MaxMemorySize"));
E
Eric Blake 已提交
6234
            ret = false;
6235
        }
6236 6237
    }

6238 6239 6240 6241
    virDomainFree(dom);
    return ret;
}

6242 6243 6244 6245 6246
/*
 * "blkiotune" command
 */
static const vshCmdInfo info_blkiotune[] = {
    {"help", N_("Get or set blkio parameters")},
E
Eric Blake 已提交
6247 6248 6249
    {"desc", N_("Get or set the current blkio parameters for a guest"
                " domain.\n"
                "    To get the blkio parameters use following command: \n\n"
6250 6251 6252 6253 6254 6255 6256 6257
                "    virsh # blkiotune <domain>")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_blkiotune[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"weight", VSH_OT_INT, VSH_OFLAG_NONE,
     N_("IO Weight in range [100, 1000]")},
6258 6259
    {"device-weights", VSH_OT_STRING, VSH_OFLAG_NONE,
     N_("per-device IO Weights, in the form of /path/to/device,weight,...")},
H
Hu Tao 已提交
6260 6261 6262
    {"config", VSH_OT_BOOL, 0, N_("affect next boot")},
    {"live", VSH_OT_BOOL, 0, N_("affect running domain")},
    {"current", VSH_OT_BOOL, 0, N_("affect current domain")},
6263 6264 6265
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
6266
static bool
6267 6268 6269
cmdBlkiotune(vshControl * ctl, const vshCmd * cmd)
{
    virDomainPtr dom;
6270
    const char *device_weight = NULL;
6271 6272
    int weight = 0;
    int nparams = 0;
6273
    int rv = 0;
6274
    unsigned int i = 0;
6275
    virTypedParameterPtr params = NULL, temp = NULL;
E
Eric Blake 已提交
6276
    bool ret = false;
H
Hu Tao 已提交
6277
    unsigned int flags = 0;
6278 6279 6280
    bool current = vshCommandOptBool(cmd, "current");
    bool config = vshCommandOptBool(cmd, "config");
    bool live = vshCommandOptBool(cmd, "live");
H
Hu Tao 已提交
6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293

    if (current) {
        if (live || config) {
            vshError(ctl, "%s", _("--current must be specified exclusively"));
            return false;
        }
        flags = VIR_DOMAIN_AFFECT_CURRENT;
    } else {
        if (config)
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
        if (live)
            flags |= VIR_DOMAIN_AFFECT_LIVE;
    }
6294 6295

    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
6296
        return false;
6297 6298

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
6299
        return false;
6300

6301
    if ((rv = vshCommandOptInt(cmd, "weight", &weight)) < 0) {
6302 6303 6304 6305 6306
        vshError(ctl, "%s",
                 _("Unable to parse integer parameter"));
        goto cleanup;
    }

6307
    if (rv > 0) {
6308
        nparams++;
6309
        if (weight <= 0) {
6310 6311 6312 6313 6314
            vshError(ctl, _("Invalid value of %d for I/O weight"), weight);
            goto cleanup;
        }
    }

6315 6316 6317 6318 6319 6320 6321 6322 6323 6324
    rv = vshCommandOptString(cmd, "device-weights", &device_weight);
    if (rv < 0) {
        vshError(ctl, "%s",
                 _("Unable to parse string parameter"));
        goto cleanup;
    }
    if (rv > 0) {
        nparams++;
    }

6325 6326
    if (nparams == 0) {
        /* get the number of blkio parameters */
H
Hu Tao 已提交
6327
        if (virDomainGetBlkioParameters(dom, NULL, &nparams, flags) != 0) {
6328 6329 6330 6331 6332 6333 6334
            vshError(ctl, "%s",
                     _("Unable to get number of blkio parameters"));
            goto cleanup;
        }

        if (nparams == 0) {
            /* nothing to output */
E
Eric Blake 已提交
6335
            ret = true;
6336 6337 6338 6339 6340
            goto cleanup;
        }

        /* now go get all the blkio parameters */
        params = vshCalloc(ctl, nparams, sizeof(*params));
H
Hu Tao 已提交
6341
        if (virDomainGetBlkioParameters(dom, params, &nparams, flags) != 0) {
6342 6343 6344 6345 6346
            vshError(ctl, "%s", _("Unable to get blkio parameters"));
            goto cleanup;
        }

        for (i = 0; i < nparams; i++) {
6347 6348 6349
            char *str = vshGetTypedParamValue(ctl, &params[i]);
            vshPrint(ctl, "%-15s: %s\n", params[i].field, str);
            VIR_FREE(str);
6350 6351 6352 6353 6354 6355 6356
        }
    } else {
        /* set the blkio parameters */
        params = vshCalloc(ctl, nparams, sizeof(*params));

        for (i = 0; i < nparams; i++) {
            temp = &params[i];
6357
            temp->type = VIR_TYPED_PARAM_UINT;
6358 6359 6360

            if (weight) {
                temp->value.ui = weight;
6361 6362 6363
                if (!virStrcpy(temp->field, VIR_DOMAIN_BLKIO_WEIGHT,
                               sizeof(temp->field)))
                    goto cleanup;
6364 6365
                weight = 0;
            } else if (device_weight) {
6366 6367 6368 6369 6370
                temp->value.s = vshStrdup(ctl, device_weight);
                temp->type = VIR_TYPED_PARAM_STRING;
                if (!virStrcpy(temp->field, VIR_DOMAIN_BLKIO_DEVICE_WEIGHT,
                               sizeof(temp->field)))
                    goto cleanup;
6371
                device_weight = NULL;
6372 6373
            }
        }
6374 6375

        if (virDomainSetBlkioParameters(dom, params, nparams, flags) < 0) {
6376
            vshError(ctl, "%s", _("Unable to change blkio parameters"));
6377 6378
            goto cleanup;
        }
6379 6380
    }

6381 6382
    ret = true;

6383
  cleanup:
6384
    virTypedParameterArrayClear(params, nparams);
6385 6386 6387 6388 6389
    VIR_FREE(params);
    virDomainFree(dom);
    return ret;
}

6390 6391 6392 6393
/*
 * "memtune" command
 */
static const vshCmdInfo info_memtune[] = {
6394
    {"help", N_("Get or set memory parameters")},
E
Eric Blake 已提交
6395 6396 6397
    {"desc", N_("Get or set the current memory parameters for a guest"
                " domain.\n"
                "    To get the memory parameters use following command: \n\n"
6398 6399 6400 6401 6402 6403
                "    virsh # memtune <domain>")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_memtune[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
6404
    {"hard-limit", VSH_OT_INT, VSH_OFLAG_NONE,
E
Eric Blake 已提交
6405
     N_("Max memory, as scaled integer (default KiB)")},
6406
    {"soft-limit", VSH_OT_INT, VSH_OFLAG_NONE,
E
Eric Blake 已提交
6407
     N_("Memory during contention, as scaled integer (default KiB)")},
6408
    {"swap-hard-limit", VSH_OT_INT, VSH_OFLAG_NONE,
E
Eric Blake 已提交
6409
     N_("Max memory plus swap, as scaled integer (default KiB)")},
6410
    {"min-guarantee", VSH_OT_INT, VSH_OFLAG_NONE,
E
Eric Blake 已提交
6411
     N_("Min guaranteed memory, as scaled integer (default KiB)")},
6412 6413 6414
    {"config", VSH_OT_BOOL, 0, N_("affect next boot")},
    {"live", VSH_OT_BOOL, 0, N_("affect running domain")},
    {"current", VSH_OT_BOOL, 0, N_("affect current domain")},
6415 6416 6417
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441
static int
vshMemtuneGetSize(const vshCmd *cmd, const char *name, long long *value)
{
    int ret;
    unsigned long long tmp;
    const char *str;
    char *end;

    ret = vshCommandOptString(cmd, name, &str);
    if (ret <= 0)
        return ret;
    if (virStrToLong_ll(str, &end, 10, value) < 0)
        return -1;
    if (*value < 0) {
        *value = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;
        return 1;
    }
    tmp = *value;
    if (virScaleInteger(&tmp, end, 1024, LLONG_MAX) < 0)
        return -1;
    *value = VIR_DIV_UP(tmp, 1024);
    return 0;
}

E
Eric Blake 已提交
6442
static bool
E
Eric Blake 已提交
6443
cmdMemtune(vshControl *ctl, const vshCmd *cmd)
6444 6445
{
    virDomainPtr dom;
6446 6447
    long long hard_limit = 0, soft_limit = 0, swap_hard_limit = 0;
    long long min_guarantee = 0;
6448 6449
    int nparams = 0;
    unsigned int i = 0;
6450
    virTypedParameterPtr params = NULL, temp = NULL;
E
Eric Blake 已提交
6451
    bool ret = false;
6452
    unsigned int flags = 0;
6453 6454 6455
    bool current = vshCommandOptBool(cmd, "current");
    bool config = vshCommandOptBool(cmd, "config");
    bool live = vshCommandOptBool(cmd, "live");
6456 6457 6458 6459 6460 6461

    if (current) {
        if (live || config) {
            vshError(ctl, "%s", _("--current must be specified exclusively"));
            return false;
        }
6462
        flags = VIR_DOMAIN_AFFECT_CURRENT;
6463 6464
    } else {
        if (config)
6465
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
6466
        if (live)
6467
            flags |= VIR_DOMAIN_AFFECT_LIVE;
6468
    }
6469 6470

    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
6471
        return false;
6472 6473

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
6474
        return false;
6475

E
Eric Blake 已提交
6476 6477 6478 6479
    if (vshMemtuneGetSize(cmd, "hard-limit", &hard_limit) < 0 ||
        vshMemtuneGetSize(cmd, "soft-limit", &soft_limit) < 0 ||
        vshMemtuneGetSize(cmd, "swap-hard-limit", &swap_hard_limit) < 0 ||
        vshMemtuneGetSize(cmd, "min-guarantee", &min_guarantee) < 0) {
6480 6481 6482 6483 6484
        vshError(ctl, "%s",
                 _("Unable to parse integer parameter"));
        goto cleanup;
    }

6485 6486 6487 6488 6489 6490 6491 6492 6493
    if (hard_limit)
        nparams++;

    if (soft_limit)
        nparams++;

    if (swap_hard_limit)
        nparams++;

6494 6495 6496
    if (min_guarantee)
        nparams++;

6497 6498
    if (nparams == 0) {
        /* get the number of memory parameters */
6499
        if (virDomainGetMemoryParameters(dom, NULL, &nparams, flags) != 0) {
6500 6501 6502 6503 6504
            vshError(ctl, "%s",
                     _("Unable to get number of memory parameters"));
            goto cleanup;
        }

6505 6506
        if (nparams == 0) {
            /* nothing to output */
E
Eric Blake 已提交
6507
            ret = true;
6508 6509 6510
            goto cleanup;
        }

6511
        /* now go get all the memory parameters */
E
Eric Blake 已提交
6512
        params = vshCalloc(ctl, nparams, sizeof(*params));
6513
        if (virDomainGetMemoryParameters(dom, params, &nparams, flags) != 0) {
6514 6515 6516 6517 6518
            vshError(ctl, "%s", _("Unable to get memory parameters"));
            goto cleanup;
        }

        for (i = 0; i < nparams; i++) {
6519 6520 6521 6522 6523 6524 6525
            if (params[i].type == VIR_TYPED_PARAM_ULLONG &&
                params[i].value.ul == VIR_DOMAIN_MEMORY_PARAM_UNLIMITED) {
                vshPrint(ctl, "%-15s: %s\n", params[i].field, _("unlimited"));
            } else {
                char *str = vshGetTypedParamValue(ctl, &params[i]);
                vshPrint(ctl, "%-15s: %s\n", params[i].field, str);
                VIR_FREE(str);
6526 6527 6528
            }
        }

E
Eric Blake 已提交
6529
        ret = true;
6530 6531
    } else {
        /* set the memory parameters */
E
Eric Blake 已提交
6532
        params = vshCalloc(ctl, nparams, sizeof(*params));
6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543

        for (i = 0; i < nparams; i++) {
            temp = &params[i];

            /*
             * Some magic here, this is used to fill the params structure with
             * the valid arguments passed, after filling the particular
             * argument we purposely make them 0, so on the next pass it goes
             * to the next valid argument and so on.
             */
            if (soft_limit) {
E
Eric Blake 已提交
6544 6545 6546 6547 6548
                if (virTypedParameterAssign(temp,
                                            VIR_DOMAIN_MEMORY_SOFT_LIMIT,
                                            VIR_TYPED_PARAM_ULLONG,
                                            soft_limit) < 0)
                    goto error;
6549 6550
                soft_limit = 0;
            } else if (hard_limit) {
E
Eric Blake 已提交
6551 6552 6553 6554 6555
                if (virTypedParameterAssign(temp,
                                            VIR_DOMAIN_MEMORY_HARD_LIMIT,
                                            VIR_TYPED_PARAM_ULLONG,
                                            hard_limit) < 0)
                    goto error;
6556 6557
                hard_limit = 0;
            } else if (swap_hard_limit) {
E
Eric Blake 已提交
6558 6559 6560 6561 6562
                if (virTypedParameterAssign(temp,
                                            VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT,
                                            VIR_TYPED_PARAM_ULLONG,
                                            swap_hard_limit) < 0)
                    goto error;
6563
                swap_hard_limit = 0;
6564
            } else if (min_guarantee) {
E
Eric Blake 已提交
6565 6566 6567 6568 6569
                if (virTypedParameterAssign(temp,
                                            VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                                            VIR_TYPED_PARAM_ULLONG,
                                            min_guarantee) < 0)
                    goto error;
6570
                min_guarantee = 0;
6571
            }
6572 6573 6574 6575

            /* If the user has passed -1, we interpret it as unlimited */
            if (temp->value.ul == -1)
                temp->value.ul = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;
6576
        }
6577
        if (virDomainSetMemoryParameters(dom, params, nparams, flags) != 0)
E
Eric Blake 已提交
6578
            goto error;
6579
        else
E
Eric Blake 已提交
6580
            ret = true;
6581 6582
    }

E
Eric Blake 已提交
6583
cleanup:
E
Eric Blake 已提交
6584
    VIR_FREE(params);
6585 6586
    virDomainFree(dom);
    return ret;
E
Eric Blake 已提交
6587 6588 6589 6590

error:
    vshError(ctl, "%s", _("Unable to change memory parameters"));
    goto cleanup;
6591 6592
}

H
Hu Tao 已提交
6593 6594 6595 6596 6597
/*
 * "numatune" command
 */
static const vshCmdInfo info_numatune[] = {
    {"help", N_("Get or set numa parameters")},
E
Eric Blake 已提交
6598 6599 6600
    {"desc", N_("Get or set the current numa parameters for a guest"
                " domain.\n"
                "    To get the numa parameters use following command: \n\n"
H
Hu Tao 已提交
6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627
                "    virsh # numatune <domain>")},
    {NULL, NULL}

};

static const vshCmdOptDef opts_numatune[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"mode", VSH_OT_DATA, VSH_OFLAG_NONE,
     N_("NUMA mode, one of strict, preferred and interleave")},
    {"nodeset", VSH_OT_DATA, VSH_OFLAG_NONE,
     N_("NUMA node selections to set")},
    {"config", VSH_OT_BOOL, 0, N_("affect next boot")},
    {"live", VSH_OT_BOOL, 0, N_("affect running domain")},
    {"current", VSH_OT_BOOL, 0, N_("affect current domain")},
    {NULL, 0, 0, NULL}
};

static bool
cmdNumatune(vshControl * ctl, const vshCmd * cmd)
{
    virDomainPtr dom;
    int nparams = 0;
    unsigned int i = 0;
    virTypedParameterPtr params = NULL, temp = NULL;
    const char *nodeset = NULL;
    bool ret = false;
    unsigned int flags = 0;
6628 6629 6630
    bool current = vshCommandOptBool(cmd, "current");
    bool config = vshCommandOptBool(cmd, "config");
    bool live = vshCommandOptBool(cmd, "live");
H
Hu Tao 已提交
6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750
    const char *mode = NULL;

    if (current) {
        if (live || config) {
            vshError(ctl, "%s", _("--current must be specified exclusively"));
            return false;
        }
        flags = VIR_DOMAIN_AFFECT_CURRENT;
    } else {
        if (config)
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
        if (live)
            flags |= VIR_DOMAIN_AFFECT_LIVE;
    }

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

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
        return false;

    if (vshCommandOptString(cmd, "nodeset", &nodeset) < 0) {
        vshError(ctl, "%s", _("Unable to parse nodeset."));
        virDomainFree(dom);
        return false;
    }
    if (nodeset)
        nparams++;
    if (vshCommandOptString(cmd, "mode", &mode) < 0) {
        vshError(ctl, "%s", _("Unable to parse mode."));
        virDomainFree(dom);
        return false;
    }
    if (mode)
        nparams++;

    if (nparams == 0) {
        /* get the number of numa parameters */
        if (virDomainGetNumaParameters(dom, NULL, &nparams, flags) != 0) {
            vshError(ctl, "%s",
                     _("Unable to get number of memory parameters"));
            goto cleanup;
        }

        if (nparams == 0) {
            /* nothing to output */
            ret = true;
            goto cleanup;
        }

        /* now go get all the numa parameters */
        params = vshCalloc(ctl, nparams, sizeof(*params));
        if (virDomainGetNumaParameters(dom, params, &nparams, flags) != 0) {
            vshError(ctl, "%s", _("Unable to get numa parameters"));
            goto cleanup;
        }

        for (i = 0; i < nparams; i++) {
            if (params[i].type == VIR_TYPED_PARAM_INT &&
                STREQ(params[i].field, VIR_DOMAIN_NUMA_MODE)) {
                vshPrint(ctl, "%-15s: %s\n", params[i].field,
                         virDomainNumatuneMemModeTypeToString(params[i].value.i));
            } else {
                char *str = vshGetTypedParamValue(ctl, &params[i]);
                vshPrint(ctl, "%-15s: %s\n", params[i].field, str);
                VIR_FREE(str);
            }
        }

        ret = true;
    } else {
        /* set the numa parameters */
        params = vshCalloc(ctl, nparams, sizeof(*params));

        for (i = 0; i < nparams; i++) {
            temp = &params[i];

            /*
             * Some magic here, this is used to fill the params structure with
             * the valid arguments passed, after filling the particular
             * argument we purposely make them 0, so on the next pass it goes
             * to the next valid argument and so on.
             */
            if (mode) {
                /* Accept string or integer, in case server
                 * understands newer integer than what strings we were
                 * compiled with */
                if ((temp->value.i =
                    virDomainNumatuneMemModeTypeFromString(mode)) < 0 &&
                    virStrToLong_i(mode, NULL, 0, &temp->value.i) < 0) {
                    vshError(ctl, _("Invalid mode: %s"), mode);
                    goto cleanup;
                }
                if (!virStrcpy(temp->field, VIR_DOMAIN_NUMA_MODE,
                               sizeof(temp->field)))
                    goto cleanup;
                temp->type = VIR_TYPED_PARAM_INT;
                mode = NULL;
            } else if (nodeset) {
                temp->value.s = vshStrdup(ctl, nodeset);
                temp->type = VIR_TYPED_PARAM_STRING;
                if (!virStrcpy(temp->field, VIR_DOMAIN_NUMA_NODESET,
                               sizeof(temp->field)))
                    goto cleanup;
                nodeset = NULL;
            }
        }
        if (virDomainSetNumaParameters(dom, params, nparams, flags) != 0)
            vshError(ctl, "%s", _("Unable to change numa parameters"));
        else
            ret = true;
    }

  cleanup:
    virTypedParameterArrayClear(params, nparams);
    VIR_FREE(params);
    virDomainFree(dom);
    return ret;
}

6751 6752 6753
/*
 * "nodeinfo" command
 */
6754
static const vshCmdInfo info_nodeinfo[] = {
6755 6756
    {"help", N_("node information")},
    {"desc", N_("Returns basic information about the node.")},
6757 6758 6759
    {NULL, NULL}
};

E
Eric Blake 已提交
6760
static bool
6761
cmdNodeinfo(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
6762 6763
{
    virNodeInfo info;
6764

6765
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
6766
        return false;
6767 6768

    if (virNodeGetInfo(ctl->conn, &info) < 0) {
6769
        vshError(ctl, "%s", _("failed to get node information"));
E
Eric Blake 已提交
6770
        return false;
6771 6772 6773 6774 6775 6776 6777 6778
    }
    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);
6779
    vshPrint(ctl, "%-20s %lu KiB\n", _("Memory size:"), info.memory);
6780

E
Eric Blake 已提交
6781
    return true;
6782 6783
}

6784 6785 6786 6787 6788
/*
 * "nodecpustats" command
 */
static const vshCmdInfo info_nodecpustats[] = {
    {"help", N_("Prints cpu stats of the node.")},
6789
    {"desc", N_("Returns cpu stats of the node, in nanoseconds.")},
6790 6791 6792 6793 6794 6795 6796 6797 6798 6799
    {NULL, NULL}
};

static const vshCmdOptDef opts_node_cpustats[] = {
    {"cpu", VSH_OT_INT, 0, N_("prints specified cpu statistics only.")},
    {"percent", VSH_OT_BOOL, 0, N_("prints by percentage during 1 second.")},
    {NULL, 0, 0, NULL}
};

static bool
6800
cmdNodeCpuStats(vshControl *ctl, const vshCmd *cmd)
6801 6802 6803 6804
{
    int i, j;
    bool flag_utilization = false;
    bool flag_percent = vshCommandOptBool(cmd, "percent");
6805 6806
    int cpuNum = VIR_NODE_CPU_STATS_ALL_CPUS;
    virNodeCPUStatsPtr params;
6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849
    int nparams = 0;
    bool ret = false;
    struct cpu_stats {
        unsigned long long user;
        unsigned long long sys;
        unsigned long long idle;
        unsigned long long iowait;
        unsigned long long util;
    } cpu_stats[2];
    double user_time, sys_time, idle_time, iowait_time, total_time;
    double usage;

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

    if (vshCommandOptInt(cmd, "cpu", &cpuNum) < 0) {
        vshError(ctl, "%s", _("Invalid value of cpuNum"));
        return false;
    }

    if (virNodeGetCPUStats(ctl->conn, cpuNum, NULL, &nparams, 0) != 0) {
        vshError(ctl, "%s",
                 _("Unable to get number of cpu stats"));
        return false;
    }
    if (nparams == 0) {
        /* nothing to output */
        return true;
    }

    memset(cpu_stats, 0, sizeof(cpu_stats));
    params = vshCalloc(ctl, nparams, sizeof(*params));

    i = 0;
    do {
        if (virNodeGetCPUStats(ctl->conn, cpuNum, params, &nparams, 0) != 0) {
            vshError(ctl, "%s", _("Unable to get node cpu stats"));
            goto cleanup;
        }

        for (j = 0; j < nparams; j++) {
            unsigned long long value = params[j].value;

6850
            if (STREQ(params[j].field, VIR_NODE_CPU_STATS_KERNEL)) {
6851
                cpu_stats[i].sys = value;
6852
            } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_USER)) {
6853
                cpu_stats[i].user = value;
6854
            } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_IDLE)) {
6855
                cpu_stats[i].idle = value;
6856
            } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_IOWAIT)) {
6857
                cpu_stats[i].iowait = value;
6858
            } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_UTILIZATION)) {
6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872
                cpu_stats[i].util = value;
                flag_utilization = true;
            }
        }

        if (flag_utilization || !flag_percent)
            break;

        i++;
        sleep(1);
    } while (i < 2);

    if (!flag_percent) {
        if (!flag_utilization) {
6873
            vshPrint(ctl, "%-15s %20llu\n", _("user:"), cpu_stats[0].user);
6874
            vshPrint(ctl, "%-15s %20llu\n", _("system:"), cpu_stats[0].sys);
6875
            vshPrint(ctl, "%-15s %20llu\n", _("idle:"), cpu_stats[0].idle);
6876 6877 6878 6879 6880 6881 6882
            vshPrint(ctl, "%-15s %20llu\n", _("iowait:"), cpu_stats[0].iowait);
        }
    } else {
        if (flag_utilization) {
            usage = cpu_stats[0].util;

            vshPrint(ctl, "%-15s %5.1lf%%\n", _("usage:"), usage);
6883
            vshPrint(ctl, "%-15s %5.1lf%%\n", _("idle:"), 100 - usage);
6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895
        } else {
            user_time   = cpu_stats[1].user   - cpu_stats[0].user;
            sys_time    = cpu_stats[1].sys    - cpu_stats[0].sys;
            idle_time   = cpu_stats[1].idle   - cpu_stats[0].idle;
            iowait_time = cpu_stats[1].iowait - cpu_stats[0].iowait;
            total_time  = user_time + sys_time + idle_time + iowait_time;

            usage = (user_time + sys_time) / total_time * 100;

            vshPrint(ctl, "%-15s %5.1lf%%\n",
                     _("usage:"), usage);
            vshPrint(ctl, "%-15s %5.1lf%%\n",
6896
                     _("user:"), user_time / total_time * 100);
6897
            vshPrint(ctl, "%-15s %5.1lf%%\n",
6898
                     _("system:"), sys_time  / total_time * 100);
6899
            vshPrint(ctl, "%-15s %5.1lf%%\n",
6900
                     _("idle:"), idle_time     / total_time * 100);
6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912
            vshPrint(ctl, "%-15s %5.1lf%%\n",
                     _("iowait:"), iowait_time   / total_time * 100);
        }
    }

    ret = true;

  cleanup:
    VIR_FREE(params);
    return ret;
}

6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931
/*
 * "nodememstats" command
 */
static const vshCmdInfo info_nodememstats[] = {
    {"help", N_("Prints memory stats of the node.")},
    {"desc", N_("Returns memory stats of the node, in kilobytes.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_node_memstats[] = {
    {"cell", VSH_OT_INT, 0, N_("prints specified cell statistics only.")},
    {NULL, 0, 0, NULL}
};

static bool
cmdNodeMemStats(vshControl *ctl, const vshCmd *cmd)
{
    int nparams = 0;
    unsigned int i = 0;
6932 6933
    int cellNum = VIR_NODE_MEMORY_STATS_ALL_CELLS;
    virNodeMemoryStatsPtr params = NULL;
6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964
    bool ret = false;

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

    if (vshCommandOptInt(cmd, "cell", &cellNum) < 0) {
        vshError(ctl, "%s", _("Invalid value of cellNum"));
        return false;
    }

    /* get the number of memory parameters */
    if (virNodeGetMemoryStats(ctl->conn, cellNum, NULL, &nparams, 0) != 0) {
        vshError(ctl, "%s",
                 _("Unable to get number of memory stats"));
        goto cleanup;
    }

    if (nparams == 0) {
        /* nothing to output */
        ret = true;
        goto cleanup;
    }

    /* now go get all the memory parameters */
    params = vshCalloc(ctl, nparams, sizeof(*params));
    if (virNodeGetMemoryStats(ctl->conn, cellNum, params, &nparams, 0) != 0) {
        vshError(ctl, "%s", _("Unable to get memory stats"));
        goto cleanup;
    }

    for (i = 0; i < nparams; i++)
6965
        vshPrint(ctl, "%-7s: %20llu KiB\n", params[i].field, params[i].value);
6966 6967 6968 6969 6970 6971 6972 6973

    ret = true;

  cleanup:
    VIR_FREE(params);
    return ret;
}

6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002
/*
 * "nodesuspend" command
 */
static const vshCmdInfo info_nodesuspend[] = {
    {"help", N_("suspend the host node for a given time duration")},
    {"desc", N_("Suspend the host node for a given time duration "
                               "and attempt to resume thereafter.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_node_suspend[] = {
    {"target", VSH_OT_DATA, VSH_OFLAG_REQ, N_("mem(Suspend-to-RAM), "
                                               "disk(Suspend-to-Disk), hybrid(Hybrid-Suspend)")},
    {"duration", VSH_OT_INT, VSH_OFLAG_REQ, N_("Suspend duration in seconds")},
    {"flags", VSH_OT_INT, VSH_OFLAG_NONE, N_("Suspend flags, 0 for default")},
    {NULL, 0, 0, NULL}
};

static bool
cmdNodeSuspend(vshControl *ctl, const vshCmd *cmd)
{
    const char *target = NULL;
    unsigned int suspendTarget;
    long long duration;
    unsigned int flags = 0;

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

7003 7004
    if (vshCommandOptString(cmd, "target", &target) < 0) {
        vshError(ctl, _("Invalid target argument"));
7005
        return false;
7006
    }
7007

7008 7009
    if (vshCommandOptLongLong(cmd, "duration", &duration) < 0) {
        vshError(ctl, _("Invalid duration argument"));
7010
        return false;
7011
    }
7012

7013 7014
    if (vshCommandOptUInt(cmd, "flags", &flags) < 0) {
        vshError(ctl, _("Invalid flags argument"));
7015
        return false;
7016
    }
7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042

    if (STREQ(target, "mem"))
        suspendTarget = VIR_NODE_SUSPEND_TARGET_MEM;
    else if (STREQ(target, "disk"))
        suspendTarget = VIR_NODE_SUSPEND_TARGET_DISK;
    else if (STREQ(target, "hybrid"))
        suspendTarget = VIR_NODE_SUSPEND_TARGET_HYBRID;
    else {
        vshError(ctl, "%s", _("Invalid target"));
        return false;
    }

    if (duration <= 0) {
        vshError(ctl, "%s", _("Invalid duration"));
        return false;
    }

    if (virNodeSuspendForDuration(ctl->conn, suspendTarget, duration,
                                  flags) < 0) {
        vshError(ctl, "%s", _("The host was not suspended"));
        return false;
    }
    return true;
}


7043 7044 7045
/*
 * "capabilities" command
 */
7046
static const vshCmdInfo info_capabilities[] = {
7047 7048
    {"help", N_("capabilities")},
    {"desc", N_("Returns capabilities of hypervisor/driver.")},
7049 7050 7051
    {NULL, NULL}
};

E
Eric Blake 已提交
7052
static bool
7053
cmdCapabilities (vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
7054 7055 7056
{
    char *caps;

7057
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
7058
        return false;
7059 7060

    if ((caps = virConnectGetCapabilities (ctl->conn)) == NULL) {
7061
        vshError(ctl, "%s", _("failed to get capabilities"));
E
Eric Blake 已提交
7062
        return false;
7063 7064
    }
    vshPrint (ctl, "%s\n", caps);
7065
    VIR_FREE(caps);
7066

E
Eric Blake 已提交
7067
    return true;
7068 7069
}

7070 7071 7072
/*
 * "dumpxml" command
 */
7073
static const vshCmdInfo info_dumpxml[] = {
7074 7075
    {"help", N_("domain information in XML")},
    {"desc", N_("Output the domain information as an XML dump to stdout.")},
7076
    {NULL, NULL}
7077 7078
};

7079
static const vshCmdOptDef opts_dumpxml[] = {
7080 7081 7082
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"inactive", VSH_OT_BOOL, 0, N_("show inactive defined XML")},
    {"security-info", VSH_OT_BOOL, 0, N_("include security sensitive information in XML dump")},
7083
    {"update-cpu", VSH_OT_BOOL, 0, N_("update guest CPU according to host CPU")},
7084
    {NULL, 0, 0, NULL}
7085 7086
};

E
Eric Blake 已提交
7087
static bool
7088
cmdDumpXML(vshControl *ctl, const vshCmd *cmd)
7089
{
7090
    virDomainPtr dom;
E
Eric Blake 已提交
7091
    bool ret = true;
7092
    char *dump;
E
Eric Blake 已提交
7093
    unsigned int flags = 0;
7094 7095 7096
    bool inactive = vshCommandOptBool(cmd, "inactive");
    bool secure = vshCommandOptBool(cmd, "security-info");
    bool update = vshCommandOptBool(cmd, "update-cpu");
7097 7098 7099 7100 7101

    if (inactive)
        flags |= VIR_DOMAIN_XML_INACTIVE;
    if (secure)
        flags |= VIR_DOMAIN_XML_SECURE;
7102 7103
    if (update)
        flags |= VIR_DOMAIN_XML_UPDATE_CPU;
7104

7105
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
7106
        return false;
7107

J
Jim Meyering 已提交
7108
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
7109
        return false;
7110

7111
    dump = virDomainGetXMLDesc(dom, flags);
7112
    if (dump != NULL) {
7113
        vshPrint(ctl, "%s", dump);
7114
        VIR_FREE(dump);
7115
    } else {
E
Eric Blake 已提交
7116
        ret = false;
7117
    }
7118

7119 7120 7121 7122
    virDomainFree(dom);
    return ret;
}

7123 7124 7125 7126
/*
 * "domxml-from-native" command
 */
static const vshCmdInfo info_domxmlfromnative[] = {
7127 7128
    {"help", N_("Convert native config to domain XML")},
    {"desc", N_("Convert native guest configuration format to domain XML format.")},
7129 7130 7131 7132
    {NULL, NULL}
};

static const vshCmdOptDef opts_domxmlfromnative[] = {
7133 7134
    {"format", VSH_OT_DATA, VSH_OFLAG_REQ, N_("source config data format")},
    {"config", VSH_OT_DATA, VSH_OFLAG_REQ, N_("config data file to import from")},
7135 7136 7137
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
7138
static bool
7139 7140
cmdDomXMLFromNative(vshControl *ctl, const vshCmd *cmd)
{
E
Eric Blake 已提交
7141
    bool ret = true;
7142 7143
    const char *format = NULL;
    const char *configFile = NULL;
7144 7145
    char *configData;
    char *xmlData;
E
Eric Blake 已提交
7146
    unsigned int flags = 0;
7147

7148
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
7149
        return false;
7150

7151 7152
    if (vshCommandOptString(cmd, "format", &format) < 0 ||
        vshCommandOptString(cmd, "config", &configFile) < 0)
E
Eric Blake 已提交
7153
        return false;
7154

7155
    if (virFileReadAll(configFile, 1024*1024, &configData) < 0)
E
Eric Blake 已提交
7156
        return false;
7157 7158 7159

    xmlData = virConnectDomainXMLFromNative(ctl->conn, format, configData, flags);
    if (xmlData != NULL) {
7160
        vshPrint(ctl, "%s", xmlData);
7161
        VIR_FREE(xmlData);
7162
    } else {
E
Eric Blake 已提交
7163
        ret = false;
7164 7165
    }

7166
    VIR_FREE(configData);
7167 7168 7169 7170 7171 7172 7173
    return ret;
}

/*
 * "domxml-to-native" command
 */
static const vshCmdInfo info_domxmltonative[] = {
7174 7175
    {"help", N_("Convert domain XML to native config")},
    {"desc", N_("Convert domain XML config to a native guest configuration format.")},
7176 7177 7178 7179
    {NULL, NULL}
};

static const vshCmdOptDef opts_domxmltonative[] = {
7180 7181
    {"format", VSH_OT_DATA, VSH_OFLAG_REQ, N_("target config data type format")},
    {"xml", VSH_OT_DATA, VSH_OFLAG_REQ, N_("xml data file to export from")},
7182 7183 7184
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
7185
static bool
7186 7187
cmdDomXMLToNative(vshControl *ctl, const vshCmd *cmd)
{
E
Eric Blake 已提交
7188
    bool ret = true;
7189 7190
    const char *format = NULL;
    const char *xmlFile = NULL;
7191 7192
    char *configData;
    char *xmlData;
E
Eric Blake 已提交
7193
    unsigned int flags = 0;
7194

7195
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
7196
        return false;
7197

7198 7199
    if (vshCommandOptString(cmd, "format", &format) < 0
        || vshCommandOptString(cmd, "xml", &xmlFile) < 0)
E
Eric Blake 已提交
7200
        return false;
7201

7202
    if (virFileReadAll(xmlFile, 1024*1024, &xmlData) < 0)
E
Eric Blake 已提交
7203
        return false;
7204 7205 7206

    configData = virConnectDomainXMLToNative(ctl->conn, format, xmlData, flags);
    if (configData != NULL) {
7207
        vshPrint(ctl, "%s", configData);
7208
        VIR_FREE(configData);
7209
    } else {
E
Eric Blake 已提交
7210
        ret = false;
7211 7212
    }

7213
    VIR_FREE(xmlData);
7214 7215 7216
    return ret;
}

K
Karel Zak 已提交
7217
/*
K
Karel Zak 已提交
7218
 * "domname" command
K
Karel Zak 已提交
7219
 */
7220
static const vshCmdInfo info_domname[] = {
7221
    {"help", N_("convert a domain id or UUID to domain name")},
7222
    {"desc", ""},
7223
    {NULL, NULL}
K
Karel Zak 已提交
7224 7225
};

7226
static const vshCmdOptDef opts_domname[] = {
7227
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain id or uuid")},
7228
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
7229 7230
};

E
Eric Blake 已提交
7231
static bool
7232
cmdDomname(vshControl *ctl, const vshCmd *cmd)
7233
{
K
Karel Zak 已提交
7234 7235
    virDomainPtr dom;

7236
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
7237
        return false;
J
Jim Meyering 已提交
7238
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, NULL,
7239
                                      VSH_BYID|VSH_BYUUID)))
E
Eric Blake 已提交
7240
        return false;
7241

K
Karel Zak 已提交
7242 7243
    vshPrint(ctl, "%s\n", virDomainGetName(dom));
    virDomainFree(dom);
E
Eric Blake 已提交
7244
    return true;
K
Karel Zak 已提交
7245 7246 7247
}

/*
K
Karel Zak 已提交
7248
 * "domid" command
K
Karel Zak 已提交
7249
 */
7250
static const vshCmdInfo info_domid[] = {
7251
    {"help", N_("convert a domain name or UUID to domain id")},
7252
    {"desc", ""},
7253
    {NULL, NULL}
K
Karel Zak 已提交
7254 7255
};

7256
static const vshCmdOptDef opts_domid[] = {
7257
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name or uuid")},
7258
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
7259 7260
};

E
Eric Blake 已提交
7261
static bool
7262
cmdDomid(vshControl *ctl, const vshCmd *cmd)
7263
{
7264
    virDomainPtr dom;
7265
    unsigned int id;
K
Karel Zak 已提交
7266

7267
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
7268
        return false;
J
Jim Meyering 已提交
7269
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, NULL,
7270
                                      VSH_BYNAME|VSH_BYUUID)))
E
Eric Blake 已提交
7271
        return false;
7272

7273 7274
    id = virDomainGetID(dom);
    if (id == ((unsigned int)-1))
7275
        vshPrint(ctl, "%s\n", "-");
7276
    else
7277
        vshPrint(ctl, "%d\n", id);
K
Karel Zak 已提交
7278
    virDomainFree(dom);
E
Eric Blake 已提交
7279
    return true;
K
Karel Zak 已提交
7280
}
7281

K
Karel Zak 已提交
7282 7283 7284
/*
 * "domuuid" command
 */
7285
static const vshCmdInfo info_domuuid[] = {
7286
    {"help", N_("convert a domain name or id to domain UUID")},
7287
    {"desc", ""},
K
Karel Zak 已提交
7288 7289 7290
    {NULL, NULL}
};

7291
static const vshCmdOptDef opts_domuuid[] = {
7292
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain id or name")},
K
Karel Zak 已提交
7293 7294 7295
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
7296
static bool
7297
cmdDomuuid(vshControl *ctl, const vshCmd *cmd)
K
Karel Zak 已提交
7298 7299
{
    virDomainPtr dom;
7300
    char uuid[VIR_UUID_STRING_BUFLEN];
K
Karel Zak 已提交
7301

7302
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
7303
        return false;
J
Jim Meyering 已提交
7304
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, NULL,
7305
                                      VSH_BYNAME|VSH_BYID)))
E
Eric Blake 已提交
7306
        return false;
7307

K
Karel Zak 已提交
7308 7309 7310
    if (virDomainGetUUIDString(dom, uuid) != -1)
        vshPrint(ctl, "%s\n", uuid);
    else
7311
        vshError(ctl, "%s", _("failed to get domain UUID"));
7312

7313
    virDomainFree(dom);
E
Eric Blake 已提交
7314
    return true;
K
Karel Zak 已提交
7315 7316
}

7317 7318 7319
/*
 * "migrate" command
 */
7320
static const vshCmdInfo info_migrate[] = {
7321 7322
    {"help", N_("migrate domain to another host")},
    {"desc", N_("Migrate domain to another host.  Add --live for live migration.")},
7323 7324 7325
    {NULL, NULL}
};

7326
static const vshCmdOptDef opts_migrate[] = {
7327 7328 7329
    {"live", VSH_OT_BOOL, 0, N_("live migration")},
    {"p2p", VSH_OT_BOOL, 0, N_("peer-2-peer migration")},
    {"direct", VSH_OT_BOOL, 0, N_("direct migration")},
E
Eric Blake 已提交
7330
    {"tunneled", VSH_OT_ALIAS, 0, "tunnelled"},
7331 7332 7333 7334
    {"tunnelled", VSH_OT_BOOL, 0, N_("tunnelled migration")},
    {"persistent", VSH_OT_BOOL, 0, N_("persist VM on destination")},
    {"undefinesource", VSH_OT_BOOL, 0, N_("undefine VM on source")},
    {"suspend", VSH_OT_BOOL, 0, N_("do not restart the domain on the destination host")},
7335 7336
    {"copy-storage-all", VSH_OT_BOOL, 0, N_("migration with non-shared storage with full disk copy")},
    {"copy-storage-inc", VSH_OT_BOOL, 0, N_("migration with non-shared storage with incremental copy (same base image shared between source and destination)")},
7337 7338
    {"change-protection", VSH_OT_BOOL, 0,
     N_("prevent any configuration changes to domain until migration ends)")},
7339
    {"unsafe", VSH_OT_BOOL, 0, N_("force migration even if it may be unsafe")},
W
Wen Congyang 已提交
7340
    {"verbose", VSH_OT_BOOL, 0, N_("display the progress of migration")},
7341
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
7342
    {"desturi", VSH_OT_DATA, VSH_OFLAG_REQ, N_("connection URI of the destination host as seen from the client(normal migration) or source(p2p migration)")},
7343 7344
    {"migrateuri", VSH_OT_DATA, 0, N_("migration URI, usually can be omitted")},
    {"dname", VSH_OT_DATA, 0, N_("rename to new name during migration (if supported)")},
W
Wen Congyang 已提交
7345
    {"timeout", VSH_OT_INT, 0, N_("force guest to suspend if live migration exceeds timeout (in seconds)")},
7346
    {"xml", VSH_OT_STRING, 0, N_("filename containing updated XML for the target")},
7347 7348 7349
    {NULL, 0, 0, NULL}
};

7350 7351
static void
doMigrate (void *opaque)
7352
{
7353
    char ret = '1';
7354
    virDomainPtr dom = NULL;
7355 7356 7357
    const char *desturi = NULL;
    const char *migrateuri = NULL;
    const char *dname = NULL;
E
Eric Blake 已提交
7358
    unsigned int flags = 0;
7359 7360 7361
    vshCtrlData *data = opaque;
    vshControl *ctl = data->ctl;
    const vshCmd *cmd = data->cmd;
7362 7363
    const char *xmlfile = NULL;
    char *xml = NULL;
7364
    sigset_t sigmask, oldsigmask;
7365 7366 7367 7368 7369

    sigemptyset(&sigmask);
    sigaddset(&sigmask, SIGINT);
    if (pthread_sigmask(SIG_BLOCK, &sigmask, &oldsigmask) < 0)
        goto out_sig;
7370

7371
    if (!vshConnectionUsability (ctl, ctl->conn))
7372
        goto out;
7373

J
Jim Meyering 已提交
7374
    if (!(dom = vshCommandOptDomain (ctl, cmd, NULL)))
7375
        goto out;
7376

7377 7378
    if (vshCommandOptString(cmd, "desturi", &desturi) <= 0 ||
        vshCommandOptString(cmd, "migrateuri", &migrateuri) < 0 ||
7379 7380
        vshCommandOptString(cmd, "dname", &dname) < 0) {
        vshError(ctl, "%s", _("missing argument"));
7381
        goto out;
7382
    }
7383

7384 7385 7386 7387 7388
    if (vshCommandOptString(cmd, "xml", &xmlfile) < 0) {
        vshError(ctl, "%s", _("malformed xml argument"));
        goto out;
    }

E
Eric Blake 已提交
7389
    if (vshCommandOptBool(cmd, "live"))
7390
        flags |= VIR_MIGRATE_LIVE;
E
Eric Blake 已提交
7391
    if (vshCommandOptBool(cmd, "p2p"))
7392
        flags |= VIR_MIGRATE_PEER2PEER;
E
Eric Blake 已提交
7393
    if (vshCommandOptBool(cmd, "tunnelled"))
7394
        flags |= VIR_MIGRATE_TUNNELLED;
C
Chris Lalancette 已提交
7395

E
Eric Blake 已提交
7396
    if (vshCommandOptBool(cmd, "persistent"))
C
Chris Lalancette 已提交
7397
        flags |= VIR_MIGRATE_PERSIST_DEST;
E
Eric Blake 已提交
7398
    if (vshCommandOptBool(cmd, "undefinesource"))
C
Chris Lalancette 已提交
7399 7400
        flags |= VIR_MIGRATE_UNDEFINE_SOURCE;

E
Eric Blake 已提交
7401
    if (vshCommandOptBool(cmd, "suspend"))
7402 7403
        flags |= VIR_MIGRATE_PAUSED;

E
Eric Blake 已提交
7404
    if (vshCommandOptBool(cmd, "copy-storage-all"))
7405 7406
        flags |= VIR_MIGRATE_NON_SHARED_DISK;

E
Eric Blake 已提交
7407
    if (vshCommandOptBool(cmd, "copy-storage-inc"))
7408 7409
        flags |= VIR_MIGRATE_NON_SHARED_INC;

E
Eric Blake 已提交
7410
    if (vshCommandOptBool(cmd, "change-protection"))
7411
        flags |= VIR_MIGRATE_CHANGE_PROTECTION;
7412

7413 7414 7415
    if (vshCommandOptBool(cmd, "unsafe"))
        flags |= VIR_MIGRATE_UNSAFE;

7416
    if (xmlfile &&
7417 7418
        virFileReadAll(xmlfile, 8192, &xml) < 0) {
        vshError(ctl, _("file '%s' doesn't exist"), xmlfile);
7419
        goto out;
7420
    }
7421

7422
    if ((flags & VIR_MIGRATE_PEER2PEER) ||
E
Eric Blake 已提交
7423
        vshCommandOptBool(cmd, "direct")) {
7424 7425
        /* For peer2peer migration or direct migration we only expect one URI
         * a libvirt URI, or a hypervisor specific URI. */
7426

7427
        if (migrateuri != NULL) {
J
Jim Fehlig 已提交
7428
            vshError(ctl, "%s", _("migrate: Unexpected migrateuri for peer2peer/direct migration"));
7429
            goto out;
7430
        }
7431

7432
        if (virDomainMigrateToURI2(dom, desturi, NULL, xml, flags, dname, 0) == 0)
7433
            ret = '0';
7434 7435 7436 7437 7438 7439
    } else {
        /* For traditional live migration, connect to the destination host directly. */
        virConnectPtr dconn = NULL;
        virDomainPtr ddom = NULL;

        dconn = virConnectOpenAuth (desturi, virConnectAuthPtrDefault, 0);
7440
        if (!dconn) goto out;
7441

7442
        ddom = virDomainMigrate2(dom, dconn, xml, flags, dname, migrateuri, 0);
7443 7444
        if (ddom) {
            virDomainFree(ddom);
7445
            ret = '0';
7446 7447 7448
        }
        virConnectClose (dconn);
    }
7449

7450 7451 7452
out:
    pthread_sigmask(SIG_SETMASK, &oldsigmask, NULL);
out_sig:
7453
    if (dom) virDomainFree (dom);
7454
    VIR_FREE(xml);
7455 7456 7457
    ignore_value(safewrite(data->writefd, &ret, sizeof(ret)));
}

W
Wen Congyang 已提交
7458
static void
7459 7460
print_job_progress(const char *label, unsigned long long remaining,
                   unsigned long long total)
W
Wen Congyang 已提交
7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479
{
    int progress;

    if (total == 0)
        /* migration has not been started */
        return;

    if (remaining == 0) {
        /* migration has completed */
        progress = 100;
    } else {
        /* use float to avoid overflow */
        progress = (int)(100.0 - remaining * 100.0 / total);
        if (progress >= 100) {
            /* migration has not completed, do not print [100 %] */
            progress = 99;
        }
    }

7480 7481
    /* see comments in vshError about why we must flush */
    fflush(stdout);
7482
    fprintf(stderr, "\r%s: [%3d %%]", label, progress);
7483
    fflush(stderr);
W
Wen Congyang 已提交
7484 7485
}

7486 7487 7488 7489 7490 7491 7492 7493 7494 7495
static void
vshMigrationTimeout(vshControl *ctl,
                    virDomainPtr dom,
                    void *opaque ATTRIBUTE_UNUSED)
{
    vshDebug(ctl, VSH_ERR_DEBUG, "suspending the domain, "
             "since migration timed out\n");
    virDomainSuspend(dom);
}

E
Eric Blake 已提交
7496
static bool
7497 7498 7499 7500 7501 7502 7503 7504
vshWatchJob(vshControl *ctl,
            virDomainPtr dom,
            bool verbose,
            int pipe_fd,
            int timeout,
            jobWatchTimeoutFunc timeout_func,
            void *opaque,
            const char *label)
7505 7506 7507
{
    struct sigaction sig_action;
    struct sigaction old_sig_action;
7508
    struct pollfd pollfd;
W
Wen Congyang 已提交
7509
    struct timeval start, curr;
7510 7511 7512 7513
    virDomainJobInfo jobinfo;
    int ret = -1;
    char retchar;
    bool functionReturn = false;
7514 7515 7516 7517
    sigset_t sigmask, oldsigmask;

    sigemptyset(&sigmask);
    sigaddset(&sigmask, SIGINT);
7518 7519 7520 7521 7522 7523 7524

    intCaught = 0;
    sig_action.sa_sigaction = vshCatchInt;
    sig_action.sa_flags = SA_SIGINFO;
    sigemptyset(&sig_action.sa_mask);
    sigaction(SIGINT, &sig_action, &old_sig_action);

7525
    pollfd.fd = pipe_fd;
7526 7527 7528
    pollfd.events = POLLIN;
    pollfd.revents = 0;

W
Wen Congyang 已提交
7529
    GETTIMEOFDAY(&start);
W
Wen Congyang 已提交
7530
    while (1) {
7531
repoll:
W
Wen Congyang 已提交
7532 7533
        ret = poll(&pollfd, 1, 500);
        if (ret > 0) {
7534 7535 7536
            if (pollfd.revents & POLLIN &&
                saferead(pipe_fd, &retchar, sizeof(retchar)) > 0 &&
                retchar == '0') {
E
Eric Blake 已提交
7537 7538 7539 7540 7541
                if (verbose) {
                    /* print [100 %] */
                    print_job_progress(label, 0, 1);
                }
                break;
7542 7543
            }
            goto cleanup;
W
Wen Congyang 已提交
7544 7545 7546 7547 7548 7549 7550
        }

        if (ret < 0) {
            if (errno == EINTR) {
                if (intCaught) {
                    virDomainAbortJob(dom);
                    intCaught = 0;
E
Eric Blake 已提交
7551
                } else {
W
Wen Congyang 已提交
7552
                    goto repoll;
E
Eric Blake 已提交
7553
                }
W
Wen Congyang 已提交
7554
            }
7555
            goto cleanup;
W
Wen Congyang 已提交
7556 7557
        }

W
Wen Congyang 已提交
7558
        GETTIMEOFDAY(&curr);
E
Eric Blake 已提交
7559 7560 7561
        if (timeout && (((int)(curr.tv_sec - start.tv_sec)  * 1000 +
                         (int)(curr.tv_usec - start.tv_usec) / 1000) >
                        timeout * 1000)) {
W
Wen Congyang 已提交
7562
            /* suspend the domain when migration timeouts. */
7563 7564 7565
            vshDebug(ctl, VSH_ERR_DEBUG, "%s timeout", label);
            if (timeout_func)
                (timeout_func)(ctl, dom, opaque);
W
Wen Congyang 已提交
7566 7567 7568
            timeout = 0;
        }

W
Wen Congyang 已提交
7569 7570 7571 7572 7573
        if (verbose) {
            pthread_sigmask(SIG_BLOCK, &sigmask, &oldsigmask);
            ret = virDomainGetJobInfo(dom, &jobinfo);
            pthread_sigmask(SIG_SETMASK, &oldsigmask, NULL);
            if (ret == 0)
7574
                print_job_progress(label, jobinfo.dataRemaining,
7575
                                   jobinfo.dataTotal);
7576 7577 7578
        }
    }

7579 7580 7581
    functionReturn = true;

cleanup:
7582
    sigaction(SIGINT, &old_sig_action, NULL);
7583 7584 7585 7586
    return functionReturn;
}

static bool
E
Eric Blake 已提交
7587
cmdMigrate(vshControl *ctl, const vshCmd *cmd)
7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600
{
    virDomainPtr dom = NULL;
    int p[2] = {-1, -1};
    virThread workerThread;
    bool verbose = false;
    bool functionReturn = false;
    int timeout = 0;
    bool live_flag = false;
    vshCtrlData data;

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
        return false;

E
Eric Blake 已提交
7601
    if (vshCommandOptBool(cmd, "verbose"))
7602 7603
        verbose = true;

E
Eric Blake 已提交
7604
    if (vshCommandOptBool(cmd, "live"))
7605 7606 7607
        live_flag = true;
    if (vshCommandOptInt(cmd, "timeout", &timeout) > 0) {
        if (! live_flag) {
E
Eric Blake 已提交
7608 7609
            vshError(ctl, "%s",
                     _("migrate: Unexpected timeout for offline migration"));
7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638
            goto cleanup;
        }

        if (timeout < 1) {
            vshError(ctl, "%s", _("migrate: Invalid timeout"));
            goto cleanup;
        }

        /* Ensure that we can multiply by 1000 without overflowing. */
        if (timeout > INT_MAX / 1000) {
            vshError(ctl, "%s", _("migrate: Timeout is too big"));
            goto cleanup;
        }
    }

    if (pipe(p) < 0)
        goto cleanup;

    data.ctl = ctl;
    data.cmd = cmd;
    data.writefd = p[1];

    if (virThreadCreate(&workerThread,
                        true,
                        doMigrate,
                        &data) < 0)
        goto cleanup;
    functionReturn = vshWatchJob(ctl, dom, verbose, p[0], timeout,
                                 vshMigrationTimeout, NULL, _("Migration"));
7639 7640 7641 7642 7643 7644 7645

    virThreadJoin(&workerThread);

cleanup:
    virDomainFree(dom);
    VIR_FORCE_CLOSE(p[0]);
    VIR_FORCE_CLOSE(p[1]);
W
Wen Congyang 已提交
7646
    return functionReturn;
7647 7648
}

7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659
/*
 * "migrate-setmaxdowntime" command
 */
static const vshCmdInfo info_migrate_setmaxdowntime[] = {
    {"help", N_("set maximum tolerable downtime")},
    {"desc", N_("Set maximum tolerable downtime of a domain which is being live-migrated to another host.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_migrate_setmaxdowntime[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
7660
    {"downtime", VSH_OT_INT, VSH_OFLAG_REQ, N_("maximum tolerable downtime (in milliseconds) for migration")},
7661 7662 7663
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
7664
static bool
7665 7666 7667
cmdMigrateSetMaxDowntime(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
7668
    long long downtime = 0;
E
Eric Blake 已提交
7669
    bool ret = false;
7670

7671
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
7672
        return false;
7673 7674

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
7675
        return false;
7676

7677 7678
    if (vshCommandOptLongLong(cmd, "downtime", &downtime) < 0 ||
        downtime < 1) {
7679 7680 7681 7682 7683 7684 7685
        vshError(ctl, "%s", _("migrate: Invalid downtime"));
        goto done;
    }

    if (virDomainMigrateSetMaxDowntime(dom, downtime, 0))
        goto done;

E
Eric Blake 已提交
7686
    ret = true;
7687 7688 7689 7690 7691 7692

done:
    virDomainFree(dom);
    return ret;
}

7693 7694 7695 7696 7697
/*
 * "migrate-setspeed" command
 */
static const vshCmdInfo info_migrate_setspeed[] = {
    {"help", N_("Set the maximum migration bandwidth")},
7698
    {"desc", N_("Set the maximum migration bandwidth (in MiB/s) for a domain "
7699 7700 7701 7702 7703 7704
                "which is being migrated to another host.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_migrate_setspeed[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
7705 7706
    {"bandwidth", VSH_OT_INT, VSH_OFLAG_REQ,
     N_("migration bandwidth limit in MiB/s")},
7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737
    {NULL, 0, 0, NULL}
};

static bool
cmdMigrateSetMaxSpeed(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
    unsigned long bandwidth = 0;
    bool ret = false;

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

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
        return false;

    if (vshCommandOptUL(cmd, "bandwidth", &bandwidth) < 0) {
        vshError(ctl, "%s", _("migrate: Invalid bandwidth"));
        goto done;
    }

    if (virDomainMigrateSetMaxSpeed(dom, bandwidth, 0) < 0)
        goto done;

    ret = true;

done:
    virDomainFree(dom);
    return ret;
}

7738 7739 7740 7741 7742
/*
 * "migrate-getspeed" command
 */
static const vshCmdInfo info_migrate_getspeed[] = {
    {"help", N_("Get the maximum migration bandwidth")},
7743
    {"desc", N_("Get the maximum migration bandwidth (in MiB/s) for a domain.")},
7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776
    {NULL, NULL}
};

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

static bool
cmdMigrateGetMaxSpeed(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
    unsigned long bandwidth;
    bool ret = false;

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

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
        return false;

    if (virDomainMigrateGetMaxSpeed(dom, &bandwidth, 0) < 0)
        goto done;

    vshPrint(ctl, "%lu\n", bandwidth);

    ret = true;

done:
    virDomainFree(dom);
    return ret;
}

7777 7778 7779 7780 7781
typedef enum {
    VSH_CMD_BLOCK_JOB_ABORT = 0,
    VSH_CMD_BLOCK_JOB_INFO = 1,
    VSH_CMD_BLOCK_JOB_SPEED = 2,
    VSH_CMD_BLOCK_JOB_PULL = 3,
E
Eric Blake 已提交
7782 7783
    VSH_CMD_BLOCK_JOB_COPY = 4,
} vshCmdBlockJobMode;
7784 7785 7786

static int
blockJobImpl(vshControl *ctl, const vshCmd *cmd,
7787 7788
             virDomainBlockJobInfoPtr info, int mode,
             virDomainPtr *pdom)
7789 7790 7791 7792 7793
{
    virDomainPtr dom = NULL;
    const char *name, *path;
    unsigned long bandwidth = 0;
    int ret = -1;
E
Eric Blake 已提交
7794
    const char *base = NULL;
7795
    unsigned int flags = 0;
7796 7797

    if (!vshConnectionUsability(ctl, ctl->conn))
7798
        goto cleanup;
7799 7800

    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
7801
        goto cleanup;
7802 7803

    if (vshCommandOptString(cmd, "path", &path) < 0)
7804
        goto cleanup;
7805

7806 7807
    if (vshCommandOptUL(cmd, "bandwidth", &bandwidth) < 0) {
        vshError(ctl, "%s", _("bandwidth must be a number"));
7808
        goto cleanup;
7809
    }
7810

E
Eric Blake 已提交
7811 7812
    switch ((vshCmdBlockJobMode) mode) {
    case  VSH_CMD_BLOCK_JOB_ABORT:
7813 7814
        if (vshCommandOptBool(cmd, "async"))
            flags |= VIR_DOMAIN_BLOCK_JOB_ABORT_ASYNC;
E
Eric Blake 已提交
7815 7816
        if (vshCommandOptBool(cmd, "pivot"))
            flags |= VIR_DOMAIN_BLOCK_JOB_ABORT_PIVOT;
7817
        ret = virDomainBlockJobAbort(dom, path, flags);
E
Eric Blake 已提交
7818 7819
        break;
    case VSH_CMD_BLOCK_JOB_INFO:
7820
        ret = virDomainGetBlockJobInfo(dom, path, info, 0);
E
Eric Blake 已提交
7821 7822
        break;
    case VSH_CMD_BLOCK_JOB_SPEED:
7823
        ret = virDomainBlockJobSetSpeed(dom, path, bandwidth, 0);
E
Eric Blake 已提交
7824 7825
        break;
    case VSH_CMD_BLOCK_JOB_PULL:
E
Eric Blake 已提交
7826 7827 7828 7829 7830 7831
        if (vshCommandOptString(cmd, "base", &base) < 0)
            goto cleanup;
        if (base)
            ret = virDomainBlockRebase(dom, path, base, bandwidth, 0);
        else
            ret = virDomainBlockPull(dom, path, bandwidth, 0);
E
Eric Blake 已提交
7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843
        break;
    case VSH_CMD_BLOCK_JOB_COPY:
        flags |= VIR_DOMAIN_BLOCK_REBASE_COPY;
        if (vshCommandOptBool(cmd, "shallow"))
            flags |= VIR_DOMAIN_BLOCK_REBASE_SHALLOW;
        if (vshCommandOptBool(cmd, "reuse-external"))
            flags |= VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT;
        if (vshCommandOptBool(cmd, "raw"))
            flags |= VIR_DOMAIN_BLOCK_REBASE_COPY_RAW;
        if (vshCommandOptString(cmd, "dest", &base) < 0)
            goto cleanup;
        ret = virDomainBlockRebase(dom, path, base, bandwidth, flags);
E
Eric Blake 已提交
7844
    }
7845

7846
cleanup:
7847 7848 7849
    if (pdom && ret == 0)
        *pdom = dom;
    else if (dom)
7850
        virDomainFree(dom);
7851 7852 7853
    return ret;
}

E
Eric Blake 已提交
7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866
/*
 * "blockcopy" command
 */
static const vshCmdInfo info_block_copy[] = {
    {"help", N_("Start a block copy operation.")},
    {"desc", N_("Populate a disk from its backing image.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_block_copy[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"path", VSH_OT_DATA, VSH_OFLAG_REQ, N_("fully-qualified path of disk")},
    {"dest", VSH_OT_DATA, VSH_OFLAG_REQ, N_("path of the copy to create")},
7867
    {"bandwidth", VSH_OT_DATA, VSH_OFLAG_NONE, N_("bandwidth limit in MiB/s")},
E
Eric Blake 已提交
7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006
    {"shallow", VSH_OT_BOOL, 0, N_("make the copy share a backing chain")},
    {"reuse-external", VSH_OT_BOOL, 0, N_("reuse existing destination")},
    {"raw", VSH_OT_BOOL, 0, N_("use raw destination file")},
    {"wait", VSH_OT_BOOL, 0, N_("wait for job to reach mirroring phase")},
    {"verbose", VSH_OT_BOOL, 0, N_("with --wait, display the progress")},
    {"timeout", VSH_OT_INT, VSH_OFLAG_NONE,
     N_("with --wait, abort if copy exceeds timeout (in seconds)")},
    {"pivot", VSH_OT_BOOL, 0, N_("with --wait, pivot when mirroring starts")},
    {"finish", VSH_OT_BOOL, 0, N_("with --wait, quit when mirroring starts")},
    {"async", VSH_OT_BOOL, 0,
     N_("with --wait, don't wait for cancel to finish")},
    {NULL, 0, 0, NULL}
};

static bool
cmdBlockCopy(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
    bool ret = false;
    bool blocking = vshCommandOptBool(cmd, "wait");
    bool verbose = vshCommandOptBool(cmd, "verbose");
    bool pivot = vshCommandOptBool(cmd, "pivot");
    bool finish = vshCommandOptBool(cmd, "finish");
    int timeout = 0;
    struct sigaction sig_action;
    struct sigaction old_sig_action;
    sigset_t sigmask;
    struct timeval start;
    struct timeval curr;
    const char *path = NULL;
    bool quit = false;
    int abort_flags = 0;

    if (blocking) {
        if (pivot && finish) {
            vshError(ctl, "%s", _("cannot mix --pivot and --finish"));
            return false;
        }
        if (vshCommandOptInt(cmd, "timeout", &timeout) > 0) {
            if (timeout < 1) {
                vshError(ctl, "%s", _("migrate: Invalid timeout"));
                return false;
            }

            /* Ensure that we can multiply by 1000 without overflowing. */
            if (timeout > INT_MAX / 1000) {
                vshError(ctl, "%s", _("migrate: Timeout is too big"));
                return false;
            }
        }
        if (vshCommandOptString(cmd, "path", &path) < 0)
            return false;
        if (vshCommandOptBool(cmd, "async"))
            abort_flags |= VIR_DOMAIN_BLOCK_JOB_ABORT_ASYNC;

        sigemptyset(&sigmask);
        sigaddset(&sigmask, SIGINT);

        intCaught = 0;
        sig_action.sa_sigaction = vshCatchInt;
        sig_action.sa_flags = SA_SIGINFO;
        sigemptyset(&sig_action.sa_mask);
        sigaction(SIGINT, &sig_action, &old_sig_action);

        GETTIMEOFDAY(&start);
    } else if (verbose || vshCommandOptBool(cmd, "timeout") ||
               vshCommandOptBool(cmd, "async") || pivot || finish) {
        vshError(ctl, "%s", _("blocking control options require --wait"));
        return false;
    }

    if (blockJobImpl(ctl, cmd, NULL, VSH_CMD_BLOCK_JOB_COPY, &dom) < 0)
        goto cleanup;

    if (!blocking) {
        vshPrint(ctl, "%s", _("Block Copy started"));
        ret = true;
        goto cleanup;
    }

    while (blocking) {
        virDomainBlockJobInfo info;
        int result = virDomainGetBlockJobInfo(dom, path, &info, 0);

        if (result <= 0) {
            vshError(ctl, _("failed to query job for disk %s"), path);
            goto cleanup;
        }
        if (verbose)
            print_job_progress(_("Block Copy"), info.end - info.cur, info.end);
        if (info.cur == info.end)
            break;

        GETTIMEOFDAY(&curr);
        if (intCaught || (timeout &&
                          (((int)(curr.tv_sec - start.tv_sec)  * 1000 +
                            (int)(curr.tv_usec - start.tv_usec) / 1000) >
                           timeout * 1000))) {
            vshDebug(ctl, VSH_ERR_DEBUG,
                     intCaught ? "interrupted" : "timeout");
            intCaught = 0;
            timeout = 0;
            quit = true;
            if (virDomainBlockJobAbort(dom, path, abort_flags) < 0) {
                vshError(ctl, _("failed to abort job for disk %s"), path);
                goto cleanup;
            }
            if (abort_flags & VIR_DOMAIN_BLOCK_JOB_ABORT_ASYNC)
                break;
        } else {
            usleep(500 * 1000);
        }
    }

    if (pivot) {
        abort_flags |= VIR_DOMAIN_BLOCK_JOB_ABORT_PIVOT;
        if (virDomainBlockJobAbort(dom, path, abort_flags) < 0) {
            vshError(ctl, _("failed to pivot job for disk %s"), path);
            goto cleanup;
        }
    } else if (finish && virDomainBlockJobAbort(dom, path, abort_flags) < 0) {
        vshError(ctl, _("failed to finish job for disk %s"), path);
        goto cleanup;
    }
    vshPrint(ctl, "\n%s",
             quit ? _("Copy aborted") :
             pivot ? _("Successfully pivoted") :
             finish ? _("Successfully copied") :
             _("Now in mirroring phase"));

    ret = true;
cleanup:
    if (dom)
        virDomainFree(dom);
    if (blocking)
        sigaction(SIGINT, &old_sig_action, NULL);
    return ret;
}

8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017
/*
 * "blockpull" command
 */
static const vshCmdInfo info_block_pull[] = {
    {"help", N_("Populate a disk from its backing image.")},
    {"desc", N_("Populate a disk from its backing image.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_block_pull[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
E
Eric Blake 已提交
8018
    {"path", VSH_OT_DATA, VSH_OFLAG_REQ, N_("fully-qualified path of disk")},
8019
    {"bandwidth", VSH_OT_DATA, VSH_OFLAG_NONE, N_("bandwidth limit in MiB/s")},
E
Eric Blake 已提交
8020 8021
    {"base", VSH_OT_DATA, VSH_OFLAG_NONE,
     N_("path of backing file in chain for a partial pull")},
8022 8023 8024 8025 8026 8027
    {"wait", VSH_OT_BOOL, 0, N_("wait for job to finish")},
    {"verbose", VSH_OT_BOOL, 0, N_("with --wait, display the progress")},
    {"timeout", VSH_OT_INT, VSH_OFLAG_NONE,
     N_("with --wait, abort if pull exceeds timeout (in seconds)")},
    {"async", VSH_OT_BOOL, 0,
     N_("with --wait, don't wait for cancel to finish")},
8028 8029 8030 8031 8032 8033
    {NULL, 0, 0, NULL}
};

static bool
cmdBlockPull(vshControl *ctl, const vshCmd *cmd)
{
8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070
    virDomainPtr dom = NULL;
    bool ret = false;
    bool blocking = vshCommandOptBool(cmd, "wait");
    bool verbose = vshCommandOptBool(cmd, "verbose");
    int timeout = 0;
    struct sigaction sig_action;
    struct sigaction old_sig_action;
    sigset_t sigmask;
    struct timeval start;
    struct timeval curr;
    const char *path = NULL;
    bool quit = false;
    int abort_flags = 0;

    if (blocking) {
        if (vshCommandOptInt(cmd, "timeout", &timeout) > 0) {
            if (timeout < 1) {
                vshError(ctl, "%s", _("invalid timeout"));
                return false;
            }

            /* Ensure that we can multiply by 1000 without overflowing. */
            if (timeout > INT_MAX / 1000) {
                vshError(ctl, "%s", _("timeout is too big"));
                return false;
            }
        }
        if (vshCommandOptString(cmd, "path", &path) < 0)
            return false;
        if (vshCommandOptBool(cmd, "async"))
            abort_flags |= VIR_DOMAIN_BLOCK_JOB_ABORT_ASYNC;

        sigemptyset(&sigmask);
        sigaddset(&sigmask, SIGINT);

        intCaught = 0;
        sig_action.sa_sigaction = vshCatchInt;
8071
        sig_action.sa_flags = SA_SIGINFO;
8072 8073 8074 8075 8076 8077 8078
        sigemptyset(&sig_action.sa_mask);
        sigaction(SIGINT, &sig_action, &old_sig_action);

        GETTIMEOFDAY(&start);
    } else if (verbose || vshCommandOptBool(cmd, "timeout") ||
               vshCommandOptBool(cmd, "async")) {
        vshError(ctl, "%s", _("blocking control options require --wait"));
8079
        return false;
8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138
    }

    if (blockJobImpl(ctl, cmd, NULL, VSH_CMD_BLOCK_JOB_PULL, &dom) < 0)
        goto cleanup;

    if (!blocking) {
        vshPrint(ctl, "%s", _("Block Pull started"));
        ret = true;
        goto cleanup;
    }

    while (blocking) {
        virDomainBlockJobInfo info;
        int result = virDomainGetBlockJobInfo(dom, path, &info, 0);

        if (result < 0) {
            vshError(ctl, _("failed to query job for disk %s"), path);
            goto cleanup;
        }
        if (result == 0)
            break;

        if (verbose)
            print_job_progress(_("Block Pull"), info.end - info.cur, info.end);

        GETTIMEOFDAY(&curr);
        if (intCaught || (timeout &&
                          (((int)(curr.tv_sec - start.tv_sec)  * 1000 +
                            (int)(curr.tv_usec - start.tv_usec) / 1000) >
                           timeout * 1000))) {
            vshDebug(ctl, VSH_ERR_DEBUG,
                     intCaught ? "interrupted" : "timeout");
            intCaught = 0;
            timeout = 0;
            quit = true;
            if (virDomainBlockJobAbort(dom, path, abort_flags) < 0) {
                vshError(ctl, _("failed to abort job for disk %s"), path);
                goto cleanup;
            }
            if (abort_flags & VIR_DOMAIN_BLOCK_JOB_ABORT_ASYNC)
                break;
        } else {
            usleep(500 * 1000);
        }
    }

    if (verbose && !quit) {
        /* printf [100 %] */
        print_job_progress(_("Block Pull"), 0, 1);
    }
    vshPrint(ctl, "\n%s", quit ? _("Pull aborted") : _("Pull complete"));

    ret = true;
cleanup:
    if (dom)
        virDomainFree(dom);
    if (blocking)
        sigaction(SIGINT, &old_sig_action, NULL);
    return ret;
8139 8140 8141
}

/*
8142
 * "blockjob" command
8143 8144
 */
static const vshCmdInfo info_block_job[] = {
8145 8146
    {"help", N_("Manage active block operations")},
    {"desc", N_("Query, adjust speed, or cancel active block operations.")},
8147 8148 8149 8150 8151
    {NULL, NULL}
};

static const vshCmdOptDef opts_block_job[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
E
Eric Blake 已提交
8152
    {"path", VSH_OT_DATA, VSH_OFLAG_REQ, N_("fully-qualified path of disk")},
8153
    {"abort", VSH_OT_BOOL, VSH_OFLAG_NONE,
E
Eric Blake 已提交
8154
     N_("abort the active job on the specified disk")},
8155 8156
    {"async", VSH_OT_BOOL, VSH_OFLAG_NONE,
     N_("don't wait for --abort to complete")},
E
Eric Blake 已提交
8157 8158
    {"pivot", VSH_OT_BOOL, VSH_OFLAG_NONE,
     N_("conclude and pivot a copy job")},
8159
    {"info", VSH_OT_BOOL, VSH_OFLAG_NONE,
E
Eric Blake 已提交
8160
     N_("get active job information for the specified disk")},
8161
    {"bandwidth", VSH_OT_DATA, VSH_OFLAG_NONE,
8162
     N_("set the Bandwidth limit in MiB/s")},
8163 8164 8165 8166 8167 8168 8169 8170 8171 8172
    {NULL, 0, 0, NULL}
};

static bool
cmdBlockJob(vshControl *ctl, const vshCmd *cmd)
{
    int mode;
    virDomainBlockJobInfo info;
    const char *type;
    int ret;
8173
    bool abortMode = (vshCommandOptBool(cmd, "abort") ||
E
Eric Blake 已提交
8174 8175
                      vshCommandOptBool(cmd, "async") ||
                      vshCommandOptBool(cmd, "pivot"));
8176 8177
    bool infoMode = vshCommandOptBool(cmd, "info");
    bool bandwidth = vshCommandOptBool(cmd, "bandwidth");
8178

8179
    if (abortMode + infoMode + bandwidth > 1) {
8180
        vshError(ctl, "%s",
8181
                 _("conflict between --abort, --info, and --bandwidth modes"));
8182 8183 8184
        return false;
    }

8185 8186 8187 8188 8189 8190 8191
    if (abortMode)
        mode = VSH_CMD_BLOCK_JOB_ABORT;
    else if (bandwidth)
        mode = VSH_CMD_BLOCK_JOB_SPEED;
    else
        mode = VSH_CMD_BLOCK_JOB_INFO;

8192
    ret = blockJobImpl(ctl, cmd, &info, mode, NULL);
8193 8194 8195 8196 8197 8198
    if (ret < 0)
        return false;

    if (ret == 0 || mode != VSH_CMD_BLOCK_JOB_INFO)
        return true;

E
Eric Blake 已提交
8199 8200
    switch (info.type) {
    case VIR_DOMAIN_BLOCK_JOB_TYPE_PULL:
8201
        type = _("Block Pull");
E
Eric Blake 已提交
8202 8203 8204 8205 8206
        break;
    case VIR_DOMAIN_BLOCK_JOB_TYPE_COPY:
        type = _("Block Copy");
        break;
    default:
8207
        type = _("Unknown job");
E
Eric Blake 已提交
8208 8209
        break;
    }
8210 8211 8212

    print_job_progress(type, info.end - info.cur, info.end);
    if (info.bandwidth != 0)
8213
        vshPrint(ctl, _("    Bandwidth limit: %lu MiB/s\n"), info.bandwidth);
8214 8215 8216
    return true;
}

8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227
/*
 * "blockresize" command
 */
static const vshCmdInfo info_block_resize[] = {
    {"help", N_("Resize block device of domain.")},
    {"desc", N_("Resize block device of domain.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_block_resize[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
E
Eric Blake 已提交
8228 8229 8230 8231
    {"path", VSH_OT_DATA, VSH_OFLAG_REQ,
     N_("Fully-qualified path of block device")},
    {"size", VSH_OT_INT, VSH_OFLAG_REQ,
     N_("New size of the block device, as scaled integer (default KiB)")},
8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251
    {NULL, 0, 0, NULL}
};

static bool
cmdBlockResize(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    const char *path = NULL;
    unsigned long long size = 0;
    unsigned int flags = 0;
    int ret = false;

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

    if (vshCommandOptString(cmd, "path", (const char **) &path) < 0) {
        vshError(ctl, "%s", _("Path must not be empty"));
        return false;
    }

E
Eric Blake 已提交
8252
    if (vshCommandOptScaledInt(cmd, "size", &size, 1024, ULLONG_MAX) < 0) {
8253 8254 8255 8256
        vshError(ctl, "%s", _("Unable to parse integer"));
        return false;
    }

E
Eric Blake 已提交
8257 8258 8259 8260 8261
    /* Prefer the older interface of KiB.  */
    if (size % 1024 == 0)
        size /= 1024;
    else
        flags |= VIR_DOMAIN_BLOCK_RESIZE_BYTES;
8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
        return false;

    if (virDomainBlockResize(dom, path, size, flags) < 0) {
        vshError(ctl, _("Failed to resize block device '%s'"), path);
    } else {
        vshPrint(ctl, _("Block device '%s' is resized"), path);
        ret = true;
    }

    virDomainFree(dom);
    return ret;
}
8276

8277 8278 8279
/*
 * "net-autostart" command
 */
8280
static const vshCmdInfo info_network_autostart[] = {
8281
    {"help", N_("autostart a network")},
8282
    {"desc",
8283
     N_("Configure a network to be automatically started at boot.")},
8284 8285 8286
    {NULL, NULL}
};

8287
static const vshCmdOptDef opts_network_autostart[] = {
8288 8289
    {"network",  VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")},
    {"disable", VSH_OT_BOOL, 0, N_("disable autostarting")},
8290 8291 8292
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
8293
static bool
8294
cmdNetworkAutostart(vshControl *ctl, const vshCmd *cmd)
8295 8296
{
    virNetworkPtr network;
8297
    const char *name;
8298 8299
    int autostart;

8300
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
8301
        return false;
8302

J
Jim Meyering 已提交
8303
    if (!(network = vshCommandOptNetwork(ctl, cmd, &name)))
E
Eric Blake 已提交
8304
        return false;
8305 8306 8307 8308

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

    if (virNetworkSetAutostart(network, autostart) < 0) {
8309
        if (autostart)
8310
            vshError(ctl, _("failed to mark network %s as autostarted"), name);
8311
        else
8312
            vshError(ctl, _("failed to unmark network %s as autostarted"), name);
8313
        virNetworkFree(network);
E
Eric Blake 已提交
8314
        return false;
8315 8316
    }

8317
    if (autostart)
8318
        vshPrint(ctl, _("Network %s marked as autostarted\n"), name);
8319
    else
8320
        vshPrint(ctl, _("Network %s unmarked as autostarted\n"), name);
8321

L
Laine Stump 已提交
8322
    virNetworkFree(network);
E
Eric Blake 已提交
8323
    return true;
8324
}
K
Karel Zak 已提交
8325

L
Lei Li 已提交
8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337
/*
 * "blkdeviotune" command
 */
static const vshCmdInfo info_blkdeviotune[] = {
    {"help", N_("Set or query a block device I/O tuning parameters.")},
    {"desc", N_("Set or query disk I/O parameters such as block throttling.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_blkdeviotune[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("block device")},
E
Eric Blake 已提交
8338 8339
    {"total_bytes_sec", VSH_OT_ALIAS, 0, "total-bytes-sec"},
    {"total-bytes-sec", VSH_OT_INT, VSH_OFLAG_NONE,
L
Lei Li 已提交
8340
     N_("total throughput limit in bytes per second")},
E
Eric Blake 已提交
8341 8342
    {"read_bytes_sec", VSH_OT_ALIAS, 0, "read-bytes-sec"},
    {"read-bytes-sec", VSH_OT_INT, VSH_OFLAG_NONE,
L
Lei Li 已提交
8343
     N_("read throughput limit in bytes per second")},
E
Eric Blake 已提交
8344 8345
    {"write_bytes_sec", VSH_OT_ALIAS, 0, "write-bytes-sec"},
    {"write-bytes-sec", VSH_OT_INT, VSH_OFLAG_NONE,
L
Lei Li 已提交
8346
     N_("write throughput limit in bytes per second")},
E
Eric Blake 已提交
8347 8348
    {"total_iops_sec", VSH_OT_ALIAS, 0, "total-iops-sec"},
    {"total-iops-sec", VSH_OT_INT, VSH_OFLAG_NONE,
L
Lei Li 已提交
8349
     N_("total I/O operations limit per second")},
E
Eric Blake 已提交
8350 8351
    {"read_iops_sec", VSH_OT_ALIAS, 0, "read-iops-sec"},
    {"read-iops-sec", VSH_OT_INT, VSH_OFLAG_NONE,
L
Lei Li 已提交
8352
     N_("read I/O operations limit per second")},
E
Eric Blake 已提交
8353 8354
    {"write_iops_sec", VSH_OT_ALIAS, 0, "write-iops-sec"},
    {"write-iops-sec", VSH_OT_INT, VSH_OFLAG_NONE,
L
Lei Li 已提交
8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369
     N_("write I/O operations limit per second")},
    {"config", VSH_OT_BOOL, 0, N_("affect next boot")},
    {"live", VSH_OT_BOOL, 0, N_("affect running domain")},
    {"current", VSH_OT_BOOL, 0, N_("affect current domain")},
    {NULL, 0, 0, NULL}
};

static bool
cmdBlkdeviotune(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
    const char *name, *disk;
    unsigned long long total_bytes_sec = 0, read_bytes_sec = 0, write_bytes_sec = 0;
    unsigned long long total_iops_sec = 0, read_iops_sec = 0, write_iops_sec = 0;
    int nparams = 0;
E
Eric Blake 已提交
8370
    virTypedParameterPtr params = NULL;
L
Lei Li 已提交
8371 8372
    unsigned int flags = 0, i = 0;
    int rv = 0;
8373 8374 8375
    bool current = vshCommandOptBool(cmd, "current");
    bool config = vshCommandOptBool(cmd, "config");
    bool live = vshCommandOptBool(cmd, "live");
L
Lei Li 已提交
8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399
    bool ret = false;

    if (current) {
        if (live || config) {
            vshError(ctl, "%s", _("--current must be specified exclusively"));
            return false;
        }
        flags = VIR_DOMAIN_AFFECT_CURRENT;
    } else {
        if (config)
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
        if (live)
            flags |= VIR_DOMAIN_AFFECT_LIVE;
    }

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

    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
        goto cleanup;

    if (vshCommandOptString(cmd, "device", &disk) < 0)
        goto cleanup;

E
Eric Blake 已提交
8400 8401
    if ((rv = vshCommandOptULongLong(cmd, "total-bytes-sec",
                                     &total_bytes_sec)) < 0) {
L
Lei Li 已提交
8402 8403 8404 8405 8406 8407 8408
        vshError(ctl, "%s",
                 _("Unable to parse integer parameter"));
        goto cleanup;
    } else if (rv > 0) {
        nparams++;
    }

E
Eric Blake 已提交
8409 8410
    if ((rv = vshCommandOptULongLong(cmd, "read-bytes-sec",
                                     &read_bytes_sec)) < 0) {
L
Lei Li 已提交
8411 8412 8413 8414 8415 8416 8417
        vshError(ctl, "%s",
                 _("Unable to parse integer parameter"));
        goto cleanup;
    } else if (rv > 0) {
        nparams++;
    }

E
Eric Blake 已提交
8418 8419
    if ((rv = vshCommandOptULongLong(cmd, "write-bytes-sec",
                                     &write_bytes_sec)) < 0) {
L
Lei Li 已提交
8420 8421 8422 8423 8424 8425 8426
        vshError(ctl, "%s",
                 _("Unable to parse integer parameter"));
        goto cleanup;
    } else if (rv > 0) {
        nparams++;
    }

E
Eric Blake 已提交
8427 8428
    if ((rv = vshCommandOptULongLong(cmd, "total-iops-sec",
                                     &total_iops_sec)) < 0) {
L
Lei Li 已提交
8429 8430 8431 8432 8433 8434 8435
        vshError(ctl, "%s",
                 _("Unable to parse integer parameter"));
        goto cleanup;
    } else if (rv > 0) {
        nparams++;
    }

E
Eric Blake 已提交
8436 8437
    if ((rv = vshCommandOptULongLong(cmd, "read-iops-sec",
                                     &read_iops_sec)) < 0) {
L
Lei Li 已提交
8438 8439 8440 8441 8442 8443 8444
        vshError(ctl, "%s",
                 _("Unable to parse integer parameter"));
        goto cleanup;
    } else if (rv > 0) {
        nparams++;
    }

E
Eric Blake 已提交
8445 8446
    if ((rv = vshCommandOptULongLong(cmd, "write-iops-sec",
                                     &write_iops_sec)) < 0) {
L
Lei Li 已提交
8447 8448 8449 8450 8451 8452 8453 8454 8455
        vshError(ctl, "%s",
                 _("Unable to parse integer parameter"));
        goto cleanup;
    } else if (rv > 0) {
        nparams++;
    }

    if (nparams == 0) {

E
Eric Blake 已提交
8456
        if (virDomainGetBlockIoTune(dom, NULL, NULL, &nparams, flags) != 0) {
L
Lei Li 已提交
8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468
            vshError(ctl, "%s",
                     _("Unable to get number of block I/O throttle parameters"));
            goto cleanup;
        }

        if (nparams == 0) {
            ret = true;
            goto cleanup;
        }

        params = vshCalloc(ctl, nparams, sizeof(*params));

E
Eric Blake 已提交
8469
        if (virDomainGetBlockIoTune(dom, disk, params, &nparams, flags) != 0) {
L
Lei Li 已提交
8470 8471 8472 8473 8474 8475
            vshError(ctl, "%s",
                     _("Unable to get block I/O throttle parameters"));
            goto cleanup;
        }

        for (i = 0; i < nparams; i++) {
8476 8477 8478
            char *str = vshGetTypedParamValue(ctl, &params[i]);
            vshPrint(ctl, "%-15s: %s\n", params[i].field, str);
            VIR_FREE(str);
L
Lei Li 已提交
8479 8480
        }

8481
        ret = true;
8482
        goto cleanup;
L
Lei Li 已提交
8483 8484 8485 8486 8487
    } else {
        /* Set the block I/O throttle, match by opt since parameters can be 0 */
        params = vshCalloc(ctl, nparams, sizeof(*params));
        i = 0;

E
Eric Blake 已提交
8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531
        if (i < nparams && vshCommandOptBool(cmd, "total-bytes-sec") &&
            virTypedParameterAssign(&params[i++],
                                    VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_BYTES_SEC,
                                    VIR_TYPED_PARAM_ULLONG,
                                    total_bytes_sec) < 0)
            goto error;

        if (i < nparams && vshCommandOptBool(cmd, "read-bytes-sec") &&
            virTypedParameterAssign(&params[i++],
                                    VIR_DOMAIN_BLOCK_IOTUNE_READ_BYTES_SEC,
                                    VIR_TYPED_PARAM_ULLONG,
                                    read_bytes_sec) < 0)
            goto error;

        if (i < nparams && vshCommandOptBool(cmd, "write-bytes-sec") &&
            virTypedParameterAssign(&params[i++],
                                    VIR_DOMAIN_BLOCK_IOTUNE_WRITE_BYTES_SEC,
                                    VIR_TYPED_PARAM_ULLONG,
                                    write_bytes_sec) < 0)
            goto error;

        if (i < nparams && vshCommandOptBool(cmd, "total-iops-sec") &&
            virTypedParameterAssign(&params[i++],
                                    VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_IOPS_SEC,
                                    VIR_TYPED_PARAM_ULLONG,
                                    total_iops_sec) < 0)
            goto error;

        if (i < nparams && vshCommandOptBool(cmd, "read-iops-sec") &&
            virTypedParameterAssign(&params[i++],
                                    VIR_DOMAIN_BLOCK_IOTUNE_READ_IOPS_SEC,
                                    VIR_TYPED_PARAM_ULLONG,
                                    read_iops_sec) < 0)
            goto error;

        if (i < nparams && vshCommandOptBool(cmd, "write-iops-sec") &&
            virTypedParameterAssign(&params[i++],
                                    VIR_DOMAIN_BLOCK_IOTUNE_WRITE_IOPS_SEC,
                                    VIR_TYPED_PARAM_ULLONG,
                                    write_iops_sec) < 0)
            goto error;

        if (virDomainSetBlockIoTune(dom, disk, params, nparams, flags) < 0)
            goto error;
L
Lei Li 已提交
8532 8533 8534 8535 8536 8537 8538 8539
    }

    ret = true;

cleanup:
    VIR_FREE(params);
    virDomainFree(dom);
    return ret;
E
Eric Blake 已提交
8540 8541 8542 8543

error:
    vshError(ctl, "%s", _("Unable to change block I/O throttle"));
    goto cleanup;
L
Lei Li 已提交
8544 8545
}

8546 8547 8548
/*
 * "net-create" command
 */
8549
static const vshCmdInfo info_network_create[] = {
8550 8551
    {"help", N_("create a network from an XML file")},
    {"desc", N_("Create a network.")},
8552 8553 8554
    {NULL, NULL}
};

8555
static const vshCmdOptDef opts_network_create[] = {
8556
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing an XML network description")},
8557 8558 8559
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
8560
static bool
8561
cmdNetworkCreate(vshControl *ctl, const vshCmd *cmd)
8562 8563
{
    virNetworkPtr network;
8564
    const char *from = NULL;
E
Eric Blake 已提交
8565
    bool ret = true;
8566
    char *buffer;
8567

8568
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
8569
        return false;
8570

8571
    if (vshCommandOptString(cmd, "file", &from) <= 0)
E
Eric Blake 已提交
8572
        return false;
8573

8574
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
E
Eric Blake 已提交
8575
        return false;
8576 8577

    network = virNetworkCreateXML(ctl->conn, buffer);
8578
    VIR_FREE(buffer);
8579

8580 8581 8582
    if (network != NULL) {
        vshPrint(ctl, _("Network %s created from %s\n"),
                 virNetworkGetName(network), from);
L
Laine Stump 已提交
8583
        virNetworkFree(network);
8584
    } else {
8585
        vshError(ctl, _("Failed to create network from %s"), from);
E
Eric Blake 已提交
8586
        ret = false;
8587 8588 8589 8590 8591 8592 8593 8594
    }
    return ret;
}


/*
 * "net-define" command
 */
8595
static const vshCmdInfo info_network_define[] = {
8596 8597
    {"help", N_("define (but don't start) a network from an XML file")},
    {"desc", N_("Define a network.")},
8598 8599 8600
    {NULL, NULL}
};

8601
static const vshCmdOptDef opts_network_define[] = {
8602
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing an XML network description")},
8603 8604 8605
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
8606
static bool
8607
cmdNetworkDefine(vshControl *ctl, const vshCmd *cmd)
8608 8609
{
    virNetworkPtr network;
8610
    const char *from = NULL;
E
Eric Blake 已提交
8611
    bool ret = true;
8612
    char *buffer;
8613

8614
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
8615
        return false;
8616

8617
    if (vshCommandOptString(cmd, "file", &from) <= 0)
E
Eric Blake 已提交
8618
        return false;
8619

8620
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
E
Eric Blake 已提交
8621
        return false;
8622 8623

    network = virNetworkDefineXML(ctl->conn, buffer);
8624
    VIR_FREE(buffer);
8625

8626 8627 8628
    if (network != NULL) {
        vshPrint(ctl, _("Network %s defined from %s\n"),
                 virNetworkGetName(network), from);
L
Laine Stump 已提交
8629
        virNetworkFree(network);
8630
    } else {
8631
        vshError(ctl, _("Failed to define network from %s"), from);
E
Eric Blake 已提交
8632
        ret = false;
8633 8634 8635 8636 8637 8638 8639 8640
    }
    return ret;
}


/*
 * "net-destroy" command
 */
8641
static const vshCmdInfo info_network_destroy[] = {
8642 8643
    {"help", N_("destroy (stop) a network")},
    {"desc", N_("Forcefully stop a given network.")},
8644 8645 8646
    {NULL, NULL}
};

8647
static const vshCmdOptDef opts_network_destroy[] = {
8648
    {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")},
8649 8650 8651
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
8652
static bool
8653
cmdNetworkDestroy(vshControl *ctl, const vshCmd *cmd)
8654 8655
{
    virNetworkPtr network;
E
Eric Blake 已提交
8656
    bool ret = true;
8657
    const char *name;
8658

8659
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
8660
        return false;
8661

J
Jim Meyering 已提交
8662
    if (!(network = vshCommandOptNetwork(ctl, cmd, &name)))
E
Eric Blake 已提交
8663
        return false;
8664 8665 8666 8667

    if (virNetworkDestroy(network) == 0) {
        vshPrint(ctl, _("Network %s destroyed\n"), name);
    } else {
8668
        vshError(ctl, _("Failed to destroy network %s"), name);
E
Eric Blake 已提交
8669
        ret = false;
8670 8671
    }

8672
    virNetworkFree(network);
8673 8674 8675 8676 8677 8678 8679
    return ret;
}


/*
 * "net-dumpxml" command
 */
8680
static const vshCmdInfo info_network_dumpxml[] = {
8681 8682
    {"help", N_("network information in XML")},
    {"desc", N_("Output the network information as an XML dump to stdout.")},
8683 8684 8685
    {NULL, NULL}
};

8686
static const vshCmdOptDef opts_network_dumpxml[] = {
8687
    {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")},
8688
    {"inactive", VSH_OT_BOOL, VSH_OFLAG_NONE, N_("network information of an inactive domain")},
8689 8690 8691
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
8692
static bool
8693
cmdNetworkDumpXML(vshControl *ctl, const vshCmd *cmd)
8694 8695
{
    virNetworkPtr network;
E
Eric Blake 已提交
8696
    bool ret = true;
8697
    char *dump;
8698 8699
    unsigned int flags = 0;
    int inactive;
8700

8701
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
8702
        return false;
8703

J
Jim Meyering 已提交
8704
    if (!(network = vshCommandOptNetwork(ctl, cmd, NULL)))
E
Eric Blake 已提交
8705
        return false;
8706

E
Eric Blake 已提交
8707
    inactive = vshCommandOptBool(cmd, "inactive");
8708 8709 8710 8711 8712
    if (inactive)
        flags |= VIR_NETWORK_XML_INACTIVE;

    dump = virNetworkGetXMLDesc(network, flags);

8713
    if (dump != NULL) {
8714
        vshPrint(ctl, "%s", dump);
8715
        VIR_FREE(dump);
8716
    } else {
E
Eric Blake 已提交
8717
        ret = false;
8718 8719 8720 8721 8722 8723
    }

    virNetworkFree(network);
    return ret;
}

O
Osier Yang 已提交
8724 8725 8726 8727 8728
/*
 * "net-info" command
 */
static const vshCmdInfo info_network_info[] = {
    {"help", N_("network information")},
E
Eric Blake 已提交
8729
    {"desc", N_("Returns basic information about the network")},
O
Osier Yang 已提交
8730 8731 8732 8733
    {NULL, NULL}
};

static const vshCmdOptDef opts_network_info[] = {
8734
    {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")},
O
Osier Yang 已提交
8735 8736 8737
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
8738
static bool
O
Osier Yang 已提交
8739 8740 8741 8742 8743 8744 8745 8746 8747 8748
cmdNetworkInfo(vshControl *ctl, const vshCmd *cmd)
{
    virNetworkPtr network;
    char uuid[VIR_UUID_STRING_BUFLEN];
    int autostart;
    int persistent = -1;
    int active = -1;
    char *bridge = NULL;

    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
8749
        return false;
O
Osier Yang 已提交
8750

8751
    if (!(network = vshCommandOptNetwork(ctl, cmd, NULL)))
E
Eric Blake 已提交
8752
        return false;
O
Osier Yang 已提交
8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777

    vshPrint(ctl, "%-15s %s\n", _("Name"), virNetworkGetName(network));

    if (virNetworkGetUUIDString(network, uuid) == 0)
        vshPrint(ctl, "%-15s %s\n", _("UUID"), uuid);

    active = virNetworkIsActive(network);
    if (active >= 0)
        vshPrint(ctl, "%-15s %s\n", _("Active:"), active? _("yes") : _("no"));

    persistent = virNetworkIsPersistent(network);
    if (persistent < 0)
        vshPrint(ctl, "%-15s %s\n", _("Persistent:"), _("unknown"));
    else
        vshPrint(ctl, "%-15s %s\n", _("Persistent:"), persistent ? _("yes") : _("no"));

    if (virNetworkGetAutostart(network, &autostart) < 0)
        vshPrint(ctl, "%-15s %s\n", _("Autostart:"), _("no autostart"));
    else
        vshPrint(ctl, "%-15s %s\n", _("Autostart:"), autostart ? _("yes") : _("no"));

    bridge = virNetworkGetBridgeName(network);
    if (bridge)
        vshPrint(ctl, "%-15s %s\n", _("Bridge:"), bridge);

8778
    VIR_FREE(bridge);
O
Osier Yang 已提交
8779
    virNetworkFree(network);
E
Eric Blake 已提交
8780
    return true;
O
Osier Yang 已提交
8781
}
8782

8783 8784 8785 8786
/*
 * "iface-edit" command
 */
static const vshCmdInfo info_interface_edit[] = {
8787 8788
    {"help", N_("edit XML configuration for a physical host interface")},
    {"desc", N_("Edit the XML configuration for a physical host interface.")},
8789 8790 8791 8792
    {NULL, NULL}
};

static const vshCmdOptDef opts_interface_edit[] = {
8793
    {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface name or MAC address")},
8794 8795 8796
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
8797
static bool
8798
cmdInterfaceEdit(vshControl *ctl, const vshCmd *cmd)
8799
{
E
Eric Blake 已提交
8800
    bool ret = false;
8801
    virInterfacePtr iface = NULL;
8802
    virInterfacePtr iface_edited = NULL;
E
Eric Blake 已提交
8803
    unsigned int flags = VIR_INTERFACE_XML_INACTIVE;
8804

8805
    if (!vshConnectionUsability(ctl, ctl->conn))
8806 8807
        goto cleanup;

8808
    iface = vshCommandOptInterface(ctl, cmd, NULL);
8809 8810 8811
    if (iface == NULL)
        goto cleanup;

W
Wen Congyang 已提交
8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822
#define EDIT_GET_XML virInterfaceGetXMLDesc(iface, flags)
#define EDIT_NOT_CHANGED \
    vshPrint(ctl, _("Interface %s XML configuration not changed.\n"),   \
             virInterfaceGetName(iface));                               \
    ret = true; goto edit_cleanup;
#define EDIT_DEFINE \
    (iface_edited = virInterfaceDefineXML(ctl->conn, doc_edited, 0))
#define EDIT_FREE \
    if (iface_edited)   \
        virInterfaceFree(iface_edited);
#include "virsh-edit.c"
8823

8824
    vshPrint(ctl, _("Interface %s XML configuration edited.\n"),
8825
             virInterfaceGetName(iface_edited));
8826

E
Eric Blake 已提交
8827
    ret = true;
8828 8829 8830

cleanup:
    if (iface)
8831 8832 8833
        virInterfaceFree(iface);
    if (iface_edited)
        virInterfaceFree(iface_edited);
8834 8835 8836 8837

    return ret;
}

8838 8839 8840
/*
 * "net-list" command
 */
8841
static const vshCmdInfo info_network_list[] = {
8842 8843
    {"help", N_("list networks")},
    {"desc", N_("Returns list of networks.")},
8844 8845 8846
    {NULL, NULL}
};

8847
static const vshCmdOptDef opts_network_list[] = {
8848 8849
    {"inactive", VSH_OT_BOOL, 0, N_("list inactive networks")},
    {"all", VSH_OT_BOOL, 0, N_("list inactive & active networks")},
8850 8851 8852
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
8853
static bool
8854
cmdNetworkList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
8855
{
8856 8857 8858
    bool inactive = vshCommandOptBool(cmd, "inactive");
    bool all = vshCommandOptBool(cmd, "all");
    bool active = !inactive || all;
8859
    int maxactive = 0, maxinactive = 0, i;
8860
    char **activeNames = NULL, **inactiveNames = NULL;
8861 8862
    inactive |= all;

8863
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
8864
        return false;
8865 8866

    if (active) {
8867 8868
        maxactive = virConnectNumOfNetworks(ctl->conn);
        if (maxactive < 0) {
8869
            vshError(ctl, "%s", _("Failed to list active networks"));
E
Eric Blake 已提交
8870
            return false;
8871
        }
8872
        if (maxactive) {
8873
            activeNames = vshMalloc(ctl, sizeof(char *) * maxactive);
8874

8875
            if ((maxactive = virConnectListNetworks(ctl->conn, activeNames,
8876
                                                    maxactive)) < 0) {
8877
                vshError(ctl, "%s", _("Failed to list active networks"));
8878
                VIR_FREE(activeNames);
E
Eric Blake 已提交
8879
                return false;
8880
            }
8881

8882
            qsort(&activeNames[0], maxactive, sizeof(char *), vshNameSorter);
8883
        }
8884 8885
    }
    if (inactive) {
8886 8887
        maxinactive = virConnectNumOfDefinedNetworks(ctl->conn);
        if (maxinactive < 0) {
8888
            vshError(ctl, "%s", _("Failed to list inactive networks"));
8889
            VIR_FREE(activeNames);
E
Eric Blake 已提交
8890
            return false;
8891
        }
8892 8893 8894
        if (maxinactive) {
            inactiveNames = vshMalloc(ctl, sizeof(char *) * maxinactive);

8895 8896 8897
            if ((maxinactive =
                     virConnectListDefinedNetworks(ctl->conn, inactiveNames,
                                                   maxinactive)) < 0) {
8898
                vshError(ctl, "%s", _("Failed to list inactive networks"));
8899 8900
                VIR_FREE(activeNames);
                VIR_FREE(inactiveNames);
E
Eric Blake 已提交
8901
                return false;
8902
            }
8903

8904
            qsort(&inactiveNames[0], maxinactive, sizeof(char*), vshNameSorter);
8905
        }
8906
    }
8907 8908
    vshPrintExtra(ctl, "%-20s %-10s %s\n", _("Name"), _("State"),
                  _("Autostart"));
8909
    vshPrintExtra(ctl, "-----------------------------------------\n");
8910 8911

    for (i = 0; i < maxactive; i++) {
8912 8913
        virNetworkPtr network =
            virNetworkLookupByName(ctl->conn, activeNames[i]);
8914 8915
        const char *autostartStr;
        int autostart = 0;
8916 8917 8918

        /* this kind of work with networks is not atomic operation */
        if (!network) {
8919
            VIR_FREE(activeNames[i]);
8920
            continue;
8921
        }
8922

8923 8924 8925
        if (virNetworkGetAutostart(network, &autostart) < 0)
            autostartStr = _("no autostart");
        else
8926
            autostartStr = autostart ? _("yes") : _("no");
8927 8928 8929 8930 8931

        vshPrint(ctl, "%-20s %-10s %-10s\n",
                 virNetworkGetName(network),
                 _("active"),
                 autostartStr);
8932
        virNetworkFree(network);
8933
        VIR_FREE(activeNames[i]);
8934 8935 8936
    }
    for (i = 0; i < maxinactive; i++) {
        virNetworkPtr network = virNetworkLookupByName(ctl->conn, inactiveNames[i]);
8937 8938
        const char *autostartStr;
        int autostart = 0;
8939 8940 8941

        /* this kind of work with networks is not atomic operation */
        if (!network) {
8942
            VIR_FREE(inactiveNames[i]);
8943
            continue;
8944
        }
8945

8946 8947 8948
        if (virNetworkGetAutostart(network, &autostart) < 0)
            autostartStr = _("no autostart");
        else
8949
            autostartStr = autostart ? _("yes") : _("no");
8950

8951
        vshPrint(ctl, "%-20s %-10s %-10s\n",
8952 8953 8954
                 inactiveNames[i],
                 _("inactive"),
                 autostartStr);
8955 8956

        virNetworkFree(network);
8957
        VIR_FREE(inactiveNames[i]);
8958
    }
8959 8960
    VIR_FREE(activeNames);
    VIR_FREE(inactiveNames);
E
Eric Blake 已提交
8961
    return true;
8962 8963 8964 8965 8966 8967
}


/*
 * "net-name" command
 */
8968
static const vshCmdInfo info_network_name[] = {
8969
    {"help", N_("convert a network UUID to network name")},
8970
    {"desc", ""},
8971 8972 8973
    {NULL, NULL}
};

8974
static const vshCmdOptDef opts_network_name[] = {
8975
    {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network uuid")},
8976 8977 8978
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
8979
static bool
8980
cmdNetworkName(vshControl *ctl, const vshCmd *cmd)
8981 8982 8983
{
    virNetworkPtr network;

8984
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
8985
        return false;
J
Jim Meyering 已提交
8986
    if (!(network = vshCommandOptNetworkBy(ctl, cmd, NULL,
8987
                                           VSH_BYUUID)))
E
Eric Blake 已提交
8988
        return false;
8989 8990 8991

    vshPrint(ctl, "%s\n", virNetworkGetName(network));
    virNetworkFree(network);
E
Eric Blake 已提交
8992
    return true;
8993 8994 8995 8996 8997 8998
}


/*
 * "net-start" command
 */
8999
static const vshCmdInfo info_network_start[] = {
9000 9001
    {"help", N_("start a (previously defined) inactive network")},
    {"desc", N_("Start a network.")},
9002 9003 9004
    {NULL, NULL}
};

9005
static const vshCmdOptDef opts_network_start[] = {
9006
    {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")},
9007 9008 9009
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
9010
static bool
9011
cmdNetworkStart(vshControl *ctl, const vshCmd *cmd)
9012 9013
{
    virNetworkPtr network;
E
Eric Blake 已提交
9014
    bool ret = true;
9015
    const char *name = NULL;
9016

9017
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
9018
        return false;
9019

9020
    if (!(network = vshCommandOptNetwork(ctl, cmd, &name)))
E
Eric Blake 已提交
9021
         return false;
9022 9023

    if (virNetworkCreate(network) == 0) {
9024
        vshPrint(ctl, _("Network %s started\n"), name);
9025
    } else {
9026
        vshError(ctl, _("Failed to start network %s"), name);
E
Eric Blake 已提交
9027
        ret = false;
9028
    }
L
Laine Stump 已提交
9029
    virNetworkFree(network);
9030 9031 9032 9033 9034 9035 9036
    return ret;
}


/*
 * "net-undefine" command
 */
9037
static const vshCmdInfo info_network_undefine[] = {
9038 9039
    {"help", N_("undefine an inactive network")},
    {"desc", N_("Undefine the configuration for an inactive network.")},
9040 9041 9042
    {NULL, NULL}
};

9043
static const vshCmdOptDef opts_network_undefine[] = {
9044
    {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")},
9045 9046 9047
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
9048
static bool
9049
cmdNetworkUndefine(vshControl *ctl, const vshCmd *cmd)
9050 9051
{
    virNetworkPtr network;
E
Eric Blake 已提交
9052
    bool ret = true;
9053
    const char *name;
9054

9055
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
9056
        return false;
9057

J
Jim Meyering 已提交
9058
    if (!(network = vshCommandOptNetwork(ctl, cmd, &name)))
E
Eric Blake 已提交
9059
        return false;
9060 9061 9062 9063

    if (virNetworkUndefine(network) == 0) {
        vshPrint(ctl, _("Network %s has been undefined\n"), name);
    } else {
9064
        vshError(ctl, _("Failed to undefine network %s"), name);
E
Eric Blake 已提交
9065
        ret = false;
9066 9067
    }

L
Laine Stump 已提交
9068
    virNetworkFree(network);
9069 9070 9071 9072 9073 9074 9075
    return ret;
}


/*
 * "net-uuid" command
 */
9076
static const vshCmdInfo info_network_uuid[] = {
9077
    {"help", N_("convert a network name to network UUID")},
9078
    {"desc", ""},
9079 9080 9081
    {NULL, NULL}
};

9082
static const vshCmdOptDef opts_network_uuid[] = {
9083
    {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name")},
9084 9085 9086
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
9087
static bool
9088
cmdNetworkUuid(vshControl *ctl, const vshCmd *cmd)
9089 9090 9091 9092
{
    virNetworkPtr network;
    char uuid[VIR_UUID_STRING_BUFLEN];

9093
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
9094
        return false;
9095

J
Jim Meyering 已提交
9096
    if (!(network = vshCommandOptNetworkBy(ctl, cmd, NULL,
9097
                                           VSH_BYNAME)))
E
Eric Blake 已提交
9098
        return false;
9099 9100 9101 9102

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

L
Laine Stump 已提交
9105
    virNetworkFree(network);
E
Eric Blake 已提交
9106
    return true;
9107 9108 9109
}


9110 9111 9112 9113 9114
/**************************************************************************/
/*
 * "iface-list" command
 */
static const vshCmdInfo info_interface_list[] = {
9115 9116
    {"help", N_("list physical host interfaces")},
    {"desc", N_("Returns list of physical host interfaces.")},
9117 9118 9119 9120
    {NULL, NULL}
};

static const vshCmdOptDef opts_interface_list[] = {
9121 9122
    {"inactive", VSH_OT_BOOL, 0, N_("list inactive interfaces")},
    {"all", VSH_OT_BOOL, 0, N_("list inactive & active interfaces")},
9123 9124
    {NULL, 0, 0, NULL}
};
E
Eric Blake 已提交
9125
static bool
9126 9127
cmdInterfaceList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
9128 9129 9130
    bool inactive = vshCommandOptBool(cmd, "inactive");
    bool all = vshCommandOptBool(cmd, "all");
    bool active = !inactive || all;
9131 9132 9133 9134
    int maxactive = 0, maxinactive = 0, i;
    char **activeNames = NULL, **inactiveNames = NULL;
    inactive |= all;

9135
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
9136
        return false;
9137 9138 9139 9140

    if (active) {
        maxactive = virConnectNumOfInterfaces(ctl->conn);
        if (maxactive < 0) {
9141
            vshError(ctl, "%s", _("Failed to list active interfaces"));
E
Eric Blake 已提交
9142
            return false;
9143 9144 9145 9146 9147 9148
        }
        if (maxactive) {
            activeNames = vshMalloc(ctl, sizeof(char *) * maxactive);

            if ((maxactive = virConnectListInterfaces(ctl->conn, activeNames,
                                                    maxactive)) < 0) {
9149
                vshError(ctl, "%s", _("Failed to list active interfaces"));
9150
                VIR_FREE(activeNames);
E
Eric Blake 已提交
9151
                return false;
9152 9153
            }

9154
            qsort(&activeNames[0], maxactive, sizeof(char *), vshNameSorter);
9155 9156 9157 9158 9159
        }
    }
    if (inactive) {
        maxinactive = virConnectNumOfDefinedInterfaces(ctl->conn);
        if (maxinactive < 0) {
9160
            vshError(ctl, "%s", _("Failed to list inactive interfaces"));
9161
            VIR_FREE(activeNames);
E
Eric Blake 已提交
9162
            return false;
9163 9164 9165 9166
        }
        if (maxinactive) {
            inactiveNames = vshMalloc(ctl, sizeof(char *) * maxinactive);

9167 9168 9169
            if ((maxinactive =
                     virConnectListDefinedInterfaces(ctl->conn, inactiveNames,
                                                     maxinactive)) < 0) {
9170
                vshError(ctl, "%s", _("Failed to list inactive interfaces"));
9171 9172
                VIR_FREE(activeNames);
                VIR_FREE(inactiveNames);
E
Eric Blake 已提交
9173
                return false;
9174 9175
            }

9176
            qsort(&inactiveNames[0], maxinactive, sizeof(char*), vshNameSorter);
9177 9178
        }
    }
9179 9180
    vshPrintExtra(ctl, "%-20s %-10s %s\n", _("Name"), _("State"),
                  _("MAC Address"));
9181 9182 9183
    vshPrintExtra(ctl, "--------------------------------------------\n");

    for (i = 0; i < maxactive; i++) {
9184 9185
        virInterfacePtr iface =
            virInterfaceLookupByName(ctl->conn, activeNames[i]);
9186 9187 9188

        /* this kind of work with interfaces is not atomic */
        if (!iface) {
9189
            VIR_FREE(activeNames[i]);
9190 9191 9192 9193 9194 9195 9196 9197
            continue;
        }

        vshPrint(ctl, "%-20s %-10s %s\n",
                 virInterfaceGetName(iface),
                 _("active"),
                 virInterfaceGetMACString(iface));
        virInterfaceFree(iface);
9198
        VIR_FREE(activeNames[i]);
9199 9200
    }
    for (i = 0; i < maxinactive; i++) {
9201 9202
        virInterfacePtr iface =
            virInterfaceLookupByName(ctl->conn, inactiveNames[i]);
9203 9204 9205

        /* this kind of work with interfaces is not atomic */
        if (!iface) {
9206
            VIR_FREE(inactiveNames[i]);
9207 9208 9209 9210 9211 9212 9213 9214
            continue;
        }

        vshPrint(ctl, "%-20s %-10s %s\n",
                 virInterfaceGetName(iface),
                 _("inactive"),
                 virInterfaceGetMACString(iface));
        virInterfaceFree(iface);
9215
        VIR_FREE(inactiveNames[i]);
9216
    }
9217 9218
    VIR_FREE(activeNames);
    VIR_FREE(inactiveNames);
E
Eric Blake 已提交
9219
    return true;
9220 9221 9222 9223 9224 9225 9226

}

/*
 * "iface-name" command
 */
static const vshCmdInfo info_interface_name[] = {
9227
    {"help", N_("convert an interface MAC address to interface name")},
9228 9229 9230 9231 9232
    {"desc", ""},
    {NULL, NULL}
};

static const vshCmdOptDef opts_interface_name[] = {
9233
    {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface mac")},
9234 9235 9236
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
9237
static bool
9238 9239 9240 9241
cmdInterfaceName(vshControl *ctl, const vshCmd *cmd)
{
    virInterfacePtr iface;

9242
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
9243
        return false;
9244
    if (!(iface = vshCommandOptInterfaceBy(ctl, cmd, NULL, NULL,
9245
                                           VSH_BYMAC)))
E
Eric Blake 已提交
9246
        return false;
9247 9248 9249

    vshPrint(ctl, "%s\n", virInterfaceGetName(iface));
    virInterfaceFree(iface);
E
Eric Blake 已提交
9250
    return true;
9251 9252 9253 9254 9255 9256
}

/*
 * "iface-mac" command
 */
static const vshCmdInfo info_interface_mac[] = {
9257
    {"help", N_("convert an interface name to interface MAC address")},
9258 9259 9260 9261 9262
    {"desc", ""},
    {NULL, NULL}
};

static const vshCmdOptDef opts_interface_mac[] = {
9263
    {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface name")},
9264 9265 9266
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
9267
static bool
9268 9269 9270 9271
cmdInterfaceMAC(vshControl *ctl, const vshCmd *cmd)
{
    virInterfacePtr iface;

9272
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
9273
        return false;
9274
    if (!(iface = vshCommandOptInterfaceBy(ctl, cmd, NULL, NULL,
9275
                                           VSH_BYNAME)))
E
Eric Blake 已提交
9276
        return false;
9277 9278 9279

    vshPrint(ctl, "%s\n", virInterfaceGetMACString(iface));
    virInterfaceFree(iface);
E
Eric Blake 已提交
9280
    return true;
9281 9282 9283 9284 9285 9286
}

/*
 * "iface-dumpxml" command
 */
static const vshCmdInfo info_interface_dumpxml[] = {
9287 9288
    {"help", N_("interface information in XML")},
    {"desc", N_("Output the physical host interface information as an XML dump to stdout.")},
9289 9290 9291 9292
    {NULL, NULL}
};

static const vshCmdOptDef opts_interface_dumpxml[] = {
9293 9294
    {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface name or MAC address")},
    {"inactive", VSH_OT_BOOL, 0, N_("show inactive defined XML")},
9295 9296 9297
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
9298
static bool
9299 9300 9301
cmdInterfaceDumpXML(vshControl *ctl, const vshCmd *cmd)
{
    virInterfacePtr iface;
E
Eric Blake 已提交
9302
    bool ret = true;
9303
    char *dump;
E
Eric Blake 已提交
9304
    unsigned int flags = 0;
9305
    bool inactive = vshCommandOptBool(cmd, "inactive");
9306 9307 9308

    if (inactive)
        flags |= VIR_INTERFACE_XML_INACTIVE;
9309

9310
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
9311
        return false;
9312 9313

    if (!(iface = vshCommandOptInterface(ctl, cmd, NULL)))
E
Eric Blake 已提交
9314
        return false;
9315

9316
    dump = virInterfaceGetXMLDesc(iface, flags);
9317
    if (dump != NULL) {
9318
        vshPrint(ctl, "%s", dump);
9319
        VIR_FREE(dump);
9320
    } else {
E
Eric Blake 已提交
9321
        ret = false;
9322 9323 9324 9325 9326 9327 9328 9329 9330 9331
    }

    virInterfaceFree(iface);
    return ret;
}

/*
 * "iface-define" command
 */
static const vshCmdInfo info_interface_define[] = {
9332 9333
    {"help", N_("define (but don't start) a physical host interface from an XML file")},
    {"desc", N_("Define a physical host interface.")},
9334 9335 9336 9337
    {NULL, NULL}
};

static const vshCmdOptDef opts_interface_define[] = {
9338
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing an XML interface description")},
9339 9340 9341
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
9342
static bool
9343 9344
cmdInterfaceDefine(vshControl *ctl, const vshCmd *cmd)
{
9345
    virInterfacePtr iface;
9346
    const char *from = NULL;
E
Eric Blake 已提交
9347
    bool ret = true;
9348 9349
    char *buffer;

9350
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
9351
        return false;
9352

9353
    if (vshCommandOptString(cmd, "file", &from) <= 0)
E
Eric Blake 已提交
9354
        return false;
9355 9356

    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
E
Eric Blake 已提交
9357
        return false;
9358

9359
    iface = virInterfaceDefineXML(ctl->conn, buffer, 0);
9360
    VIR_FREE(buffer);
9361

9362
    if (iface != NULL) {
9363
        vshPrint(ctl, _("Interface %s defined from %s\n"),
9364
                 virInterfaceGetName(iface), from);
L
Laine Stump 已提交
9365
        virInterfaceFree (iface);
9366
    } else {
9367
        vshError(ctl, _("Failed to define interface from %s"), from);
E
Eric Blake 已提交
9368
        ret = false;
9369 9370 9371 9372 9373 9374 9375 9376
    }
    return ret;
}

/*
 * "iface-undefine" command
 */
static const vshCmdInfo info_interface_undefine[] = {
9377 9378
    {"help", N_("undefine a physical host interface (remove it from configuration)")},
    {"desc", N_("undefine an interface.")},
9379 9380 9381 9382
    {NULL, NULL}
};

static const vshCmdOptDef opts_interface_undefine[] = {
9383
    {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface name or MAC address")},
9384 9385 9386
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
9387
static bool
9388 9389 9390
cmdInterfaceUndefine(vshControl *ctl, const vshCmd *cmd)
{
    virInterfacePtr iface;
E
Eric Blake 已提交
9391
    bool ret = true;
9392
    const char *name;
9393

9394
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
9395
        return false;
9396 9397

    if (!(iface = vshCommandOptInterface(ctl, cmd, &name)))
E
Eric Blake 已提交
9398
        return false;
9399 9400 9401 9402

    if (virInterfaceUndefine(iface) == 0) {
        vshPrint(ctl, _("Interface %s undefined\n"), name);
    } else {
9403
        vshError(ctl, _("Failed to undefine interface %s"), name);
E
Eric Blake 已提交
9404
        ret = false;
9405 9406 9407 9408 9409 9410 9411 9412 9413 9414
    }

    virInterfaceFree(iface);
    return ret;
}

/*
 * "iface-start" command
 */
static const vshCmdInfo info_interface_start[] = {
9415 9416
    {"help", N_("start a physical host interface (enable it / \"if-up\")")},
    {"desc", N_("start a physical host interface.")},
9417 9418 9419 9420
    {NULL, NULL}
};

static const vshCmdOptDef opts_interface_start[] = {
9421
    {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface name or MAC address")},
9422 9423 9424
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
9425
static bool
9426 9427 9428
cmdInterfaceStart(vshControl *ctl, const vshCmd *cmd)
{
    virInterfacePtr iface;
E
Eric Blake 已提交
9429
    bool ret = true;
9430
    const char *name;
9431

9432
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
9433
        return false;
9434 9435

    if (!(iface = vshCommandOptInterface(ctl, cmd, &name)))
E
Eric Blake 已提交
9436
        return false;
9437 9438 9439 9440

    if (virInterfaceCreate(iface, 0) == 0) {
        vshPrint(ctl, _("Interface %s started\n"), name);
    } else {
9441
        vshError(ctl, _("Failed to start interface %s"), name);
E
Eric Blake 已提交
9442
        ret = false;
9443 9444 9445 9446 9447 9448 9449 9450 9451 9452
    }

    virInterfaceFree(iface);
    return ret;
}

/*
 * "iface-destroy" command
 */
static const vshCmdInfo info_interface_destroy[] = {
9453
    {"help", N_("destroy a physical host interface (disable it / \"if-down\")")},
9454
    {"desc", N_("forcefully stop a physical host interface.")},
9455 9456 9457 9458
    {NULL, NULL}
};

static const vshCmdOptDef opts_interface_destroy[] = {
9459
    {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface name or MAC address")},
9460 9461 9462
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
9463
static bool
9464 9465 9466
cmdInterfaceDestroy(vshControl *ctl, const vshCmd *cmd)
{
    virInterfacePtr iface;
E
Eric Blake 已提交
9467
    bool ret = true;
9468
    const char *name;
9469

9470
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
9471
        return false;
9472 9473

    if (!(iface = vshCommandOptInterface(ctl, cmd, &name)))
E
Eric Blake 已提交
9474
        return false;
9475 9476 9477 9478

    if (virInterfaceDestroy(iface, 0) == 0) {
        vshPrint(ctl, _("Interface %s destroyed\n"), name);
    } else {
9479
        vshError(ctl, _("Failed to destroy interface %s"), name);
E
Eric Blake 已提交
9480
        ret = false;
9481 9482 9483 9484 9485 9486
    }

    virInterfaceFree(iface);
    return ret;
}

9487 9488 9489 9490 9491
/*
 * "iface-begin" command
 */
static const vshCmdInfo info_interface_begin[] = {
    {"help", N_("create a snapshot of current interfaces settings, "
Y
Yuri Chornoivan 已提交
9492
                "which can be later committed (iface-commit) or "
9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571
                "restored (iface-rollback)")},
    {"desc", N_("Create a restore point for interfaces settings")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_interface_begin[] = {
    {NULL, 0, 0, NULL}
};

static bool
cmdInterfaceBegin(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    if (!vshConnectionUsability(ctl, ctl->conn))
        return false;

    if (virInterfaceChangeBegin(ctl->conn, 0) < 0) {
        vshError(ctl, "%s", _("Failed to begin network config change transaction"));
        return false;
    }

    vshPrint(ctl, "%s", _("Network config change transaction started\n"));
    return true;
}

/*
 * "iface-commit" command
 */
static const vshCmdInfo info_interface_commit[] = {
    {"help", N_("commit changes made since iface-begin and free restore point")},
    {"desc", N_("commit changes and free restore point")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_interface_commit[] = {
    {NULL, 0, 0, NULL}
};

static bool
cmdInterfaceCommit(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    if (!vshConnectionUsability(ctl, ctl->conn))
        return false;

    if (virInterfaceChangeCommit(ctl->conn, 0) < 0) {
        vshError(ctl, "%s", _("Failed to commit network config change transaction"));
        return false;
    }

    vshPrint(ctl, "%s", _("Network config change transaction committed\n"));
    return true;
}

/*
 * "iface-rollback" command
 */
static const vshCmdInfo info_interface_rollback[] = {
    {"help", N_("rollback to previous saved configuration created via iface-begin")},
    {"desc", N_("rollback to previous restore point")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_interface_rollback[] = {
    {NULL, 0, 0, NULL}
};

static bool
cmdInterfaceRollback(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    if (!vshConnectionUsability(ctl, ctl->conn))
        return false;

    if (virInterfaceChangeRollback(ctl->conn, 0) < 0) {
        vshError(ctl, "%s", _("Failed to rollback network config change transaction"));
        return false;
    }

    vshPrint(ctl, "%s", _("Network config change transaction rolled back\n"));
    return true;
}
9572

9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766
/*
 * "iface-bridge" command
 */
static const vshCmdInfo info_interface_bridge[] = {
    {"help", N_("create a bridge device and attach an existing network device to it")},
    {"desc", N_("bridge an existing network device")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_interface_bridge[] = {
    {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("existing interface name")},
    {"bridge", VSH_OT_DATA, VSH_OFLAG_REQ, N_("new bridge device name")},
    {"no-stp", VSH_OT_BOOL, 0, N_("do not enable STP for this bridge")},
    {"delay", VSH_OT_INT, 0,
     N_("number of seconds to squelch traffic on newly connected ports")},
    {"no-start", VSH_OT_BOOL, 0, N_("don't start the bridge immediately")},
    {NULL, 0, 0, NULL}
};

static bool
cmdInterfaceBridge(vshControl *ctl, const vshCmd *cmd)
{
    bool ret = false;
    virInterfacePtr if_handle = NULL, br_handle = NULL;
    const char *if_name, *br_name;
    char *if_type = NULL, *if2_name = NULL, *delay_str = NULL;
    bool stp = false, nostart = false;
    unsigned int delay = 0;
    char *if_xml = NULL;
    xmlChar *br_xml = NULL;
    int br_xml_size;
    xmlDocPtr xml_doc = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlNodePtr top_node, br_node, if_node, cur;

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

    /* Get a handle to the original device */
    if (!(if_handle = vshCommandOptInterfaceBy(ctl, cmd, "interface",
                                               &if_name, VSH_BYNAME))) {
        goto cleanup;
    }

    /* Name for new bridge device */
    if (vshCommandOptString(cmd, "bridge", &br_name) <= 0) {
        vshError(ctl, "%s", _("Missing bridge device name in command"));
        goto cleanup;
    }

    /* make sure "new" device doesn't already exist */
    if ((br_handle = virInterfaceLookupByName(ctl->conn, br_name))) {
        vshError(ctl, _("Network device %s already exists"), br_name);
        goto cleanup;
    }

    /* use "no-stp" because we want "stp" to default true */
    stp = !vshCommandOptBool(cmd, "no-stp");

    if (vshCommandOptUInt(cmd, "delay", &delay) < 0) {
        vshError(ctl, "%s", _("Unable to parse delay parameter"));
        goto cleanup;
    }

    nostart = vshCommandOptBool(cmd, "no-start");

    /* Get the original interface into an xmlDoc */
    if (!(if_xml = virInterfaceGetXMLDesc(if_handle, VIR_INTERFACE_XML_INACTIVE)))
        goto cleanup;
    if (!(xml_doc = virXMLParseStringCtxt(if_xml,
                                          _("(interface definition)"), &ctxt))) {
        vshError(ctl, _("Failed to parse configuration of %s"), if_name);
        goto cleanup;
    }
    top_node = ctxt->node;

    /* Verify that the original device isn't already a bridge. */
    if (!(if_type = virXMLPropString(top_node, "type"))) {
        vshError(ctl, _("Existing device %s has no type"), if_name);
        goto cleanup;
    }

    if (STREQ(if_type, "bridge")) {
        vshError(ctl, _("Existing device %s is already a bridge"), if_name);
        goto cleanup;
    }

    /* verify the name in the XML matches the device name */
    if (!(if2_name = virXMLPropString(top_node, "name")) ||
        STRNEQ(if2_name, if_name)) {
        vshError(ctl, _("Interface name from config %s doesn't match given supplied name %s"),
                 if2_name, if_name);
        goto cleanup;
    }

    /* Create a <bridge> node under <interface>. */
    if (!(br_node = xmlNewChild(top_node, NULL, BAD_CAST "bridge", NULL))) {
        vshError(ctl, "%s", _("Failed to create bridge node in xml document"));
        goto cleanup;
    }

    /* Set stp and delay attributes in <bridge> according to the
     * commandline options.
     */
    if (!xmlSetProp(br_node, BAD_CAST "stp", BAD_CAST (stp ? "on" : "off"))) {
        vshError(ctl, "%s", _("Failed to set stp attribute in xml document"));
        goto cleanup;
    }

    if ((delay || stp) &&
        ((virAsprintf(&delay_str, "%d", delay) < 0) ||
         !xmlSetProp(br_node, BAD_CAST "delay", BAD_CAST delay_str))) {
        vshError(ctl, _("Failed to set bridge delay %d in xml document"), delay);
        goto cleanup;
    }

    /* Change the type of the outer/master interface to "bridge" and the
     * name to the provided bridge name.
     */
    if (!xmlSetProp(top_node, BAD_CAST "type", BAD_CAST "bridge")) {
        vshError(ctl, "%s", _("Failed to set bridge interface type to 'bridge' in xml document"));
        goto cleanup;
    }

    if (!xmlSetProp(top_node, BAD_CAST "name", BAD_CAST br_name)) {
        vshError(ctl, _("Failed to set master bridge interface name to '%s' in xml document"),
            br_name);
        goto cleanup;
    }

    /* Create an <interface> node under <bridge> that uses the
     * original interface's type and name.
     */
    if (!(if_node = xmlNewChild(br_node, NULL, BAD_CAST "interface", NULL))) {
        vshError(ctl, "%s", _("Failed to create interface node under bridge node in xml document"));
        goto cleanup;
    }

    /* set the type of the inner/slave interface to the original
     * if_type, and the name to the original if_name.
     */
    if (!xmlSetProp(if_node, BAD_CAST "type", BAD_CAST if_type)) {
        vshError(ctl, _("Failed to set new slave interface type to '%s' in xml document"),
                 if_name);
        goto cleanup;
    }

    if (!xmlSetProp(if_node, BAD_CAST "name", BAD_CAST if_name)) {
        vshError(ctl, _("Failed to set new slave interface name to '%s' in xml document"),
            br_name);
        goto cleanup;
    }

    /* Cycle through all the nodes under the original <interface>,
     * moving all <mac>, <bond> and <vlan> nodes down into the new
     * lower level <interface>.
     */
    cur = top_node->children;
    while (cur) {
        xmlNodePtr old = cur;

        cur = cur->next;
        if ((old->type == XML_ELEMENT_NODE) &&
            (xmlStrEqual(old->name, BAD_CAST "mac") ||  /* ethernet stuff to move down */
             xmlStrEqual(old->name, BAD_CAST "bond") || /* bond stuff to move down */
             xmlStrEqual(old->name, BAD_CAST "vlan"))) { /* vlan stuff to move down */
            xmlUnlinkNode(old);
            if (!xmlAddChild(if_node, old)) {
                vshError(ctl, _("Failed to move '%s' element in xml document"), old->name);
                xmlFreeNode(old);
                goto cleanup;
            }
        }
    }

    /* The document should now be fully converted; write it out to a string. */
    xmlDocDumpMemory(xml_doc, &br_xml, &br_xml_size);

    if (!br_xml || br_xml_size <= 0) {
        vshError(ctl, _("Failed to format new xml document for bridge %s"), br_name);
        goto cleanup;
    }


    /* br_xml is the new interface to define. It will automatically undefine the
     * independent original interface.
     */
    if (!(br_handle = virInterfaceDefineXML(ctl->conn, (char *) br_xml, 0))) {
        vshError(ctl, _("Failed to define new bridge interface %s"),
                 br_name);
        goto cleanup;
    }

    vshPrint(ctl, _("Created bridge %s with attached device %s\n"),
9767
             br_name, if_name);
9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874

    /* start it up unless requested not to */
    if (!nostart) {
        if (virInterfaceCreate(br_handle, 0) < 0) {
            vshError(ctl, _("Failed to start bridge interface %s"), br_name);
            goto cleanup;
        }
        vshPrint(ctl, _("Bridge interface %s started\n"), br_name);
    }

    ret = true;
 cleanup:
    if (if_handle)
       virInterfaceFree(if_handle);
    if (br_handle)
       virInterfaceFree(br_handle);
    VIR_FREE(if_xml);
    VIR_FREE(br_xml);
    VIR_FREE(if_type);
    VIR_FREE(if2_name);
    VIR_FREE(delay_str);
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml_doc);
    return ret;
}

/*
 * "iface-unbridge" command
 */
static const vshCmdInfo info_interface_unbridge[] = {
    {"help", N_("undefine a bridge device after detaching its slave device")},
    {"desc", N_("unbridge a network device")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_interface_unbridge[] = {
    {"bridge", VSH_OT_DATA, VSH_OFLAG_REQ, N_("current bridge device name")},
    {"no-start", VSH_OT_BOOL, 0,
     N_("don't start the un-slaved interface immediately (not recommended)")},
    {NULL, 0, 0, NULL}
};

static bool
cmdInterfaceUnbridge(vshControl *ctl, const vshCmd *cmd)
{
    bool ret = false;
    virInterfacePtr if_handle = NULL, br_handle = NULL;
    const char *br_name;
    char *if_type = NULL, *if_name = NULL;
    bool nostart = false;
    char *br_xml = NULL;
    xmlChar *if_xml = NULL;
    int if_xml_size;
    xmlDocPtr xml_doc = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlNodePtr top_node, br_node, if_node, cur;

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

    /* Get a handle to the original device */
    if (!(br_handle = vshCommandOptInterfaceBy(ctl, cmd, "bridge",
                                               &br_name, VSH_BYNAME))) {
        goto cleanup;
    }

    nostart = vshCommandOptBool(cmd, "no-start");

    /* Get the bridge xml into an xmlDoc */
    if (!(br_xml = virInterfaceGetXMLDesc(br_handle, VIR_INTERFACE_XML_INACTIVE)))
        goto cleanup;
    if (!(xml_doc = virXMLParseStringCtxt(br_xml,
                                          _("(bridge interface definition)"),
                                          &ctxt))) {
        vshError(ctl, _("Failed to parse configuration of %s"), br_name);
        goto cleanup;
    }
    top_node = ctxt->node;

    /* Verify that the device really is a bridge. */
    if (!(if_type = virXMLPropString(top_node, "type"))) {
        vshError(ctl, _("Existing device %s has no type"), br_name);
        goto cleanup;
    }

    if (STRNEQ(if_type, "bridge")) {
        vshError(ctl, _("Device %s is not a bridge"), br_name);
        goto cleanup;
    }
    VIR_FREE(if_type);

    /* verify the name in the XML matches the device name */
    if (!(if_name = virXMLPropString(top_node, "name")) ||
        STRNEQ(if_name, br_name)) {
        vshError(ctl, _("Interface name from config %s doesn't match given supplied name %s"),
                 if_name, br_name);
        goto cleanup;
    }
    VIR_FREE(if_name);

    /* Find the <bridge> node under <interface>. */
    if (!(br_node = virXPathNode("./bridge", ctxt))) {
        vshError(ctl, "%s", _("No bridge node in xml document"));
        goto cleanup;
    }

    if ((if_node = virXPathNode("./bridge/interface[2]", ctxt))) {
Y
Yuri Chornoivan 已提交
9875
        vshError(ctl, "%s", _("Multiple interfaces attached to bridge"));
9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985
        goto cleanup;
    }

    if (!(if_node = virXPathNode("./bridge/interface", ctxt))) {
        vshError(ctl, "%s", _("No interface attached to bridge"));
        goto cleanup;
    }

    /* Change the type and name of the outer/master interface to
     * the type/name of the attached slave interface.
     */
    if (!(if_name = virXMLPropString(if_node, "name"))) {
        vshError(ctl, _("Device attached to bridge %s has no name"), br_name);
        goto cleanup;
    }

    if (!(if_type = virXMLPropString(if_node, "type"))) {
        vshError(ctl, _("Attached device %s has no type"), if_name);
        goto cleanup;
    }

    if (!xmlSetProp(top_node, BAD_CAST "type", BAD_CAST if_type)) {
        vshError(ctl, _("Failed to set interface type to '%s' in xml document"),
                 if_type);
        goto cleanup;
    }

    if (!xmlSetProp(top_node, BAD_CAST "name", BAD_CAST if_name)) {
        vshError(ctl, _("Failed to set interface name to '%s' in xml document"),
                 if_name);
        goto cleanup;
    }

    /* Cycle through all the nodes under the attached <interface>,
     * moving all <mac>, <bond> and <vlan> nodes up into the toplevel
     * <interface>.
     */
    cur = if_node->children;
    while (cur) {
        xmlNodePtr old = cur;

        cur = cur->next;
        if ((old->type == XML_ELEMENT_NODE) &&
            (xmlStrEqual(old->name, BAD_CAST "mac") ||  /* ethernet stuff to move down */
             xmlStrEqual(old->name, BAD_CAST "bond") || /* bond stuff to move down */
             xmlStrEqual(old->name, BAD_CAST "vlan"))) { /* vlan stuff to move down */
            xmlUnlinkNode(old);
            if (!xmlAddChild(top_node, old)) {
                vshError(ctl, _("Failed to move '%s' element in xml document"), old->name);
                xmlFreeNode(old);
                goto cleanup;
            }
        }
    }

    /* The document should now be fully converted; write it out to a string. */
    xmlDocDumpMemory(xml_doc, &if_xml, &if_xml_size);

    if (!if_xml || if_xml_size <= 0) {
        vshError(ctl, _("Failed to format new xml document for un-enslaved interface %s"),
                 if_name);
        goto cleanup;
    }

    /* Destroy and Undefine the bridge device, since we otherwise
     * can't safely define the unattached device.
     */
    if (virInterfaceDestroy(br_handle, 0) < 0) {
        vshError(ctl, _("Failed to destroy bridge interface %s"), br_name);
        goto cleanup;
    }
    if (virInterfaceUndefine(br_handle) < 0) {
        vshError(ctl, _("Failed to undefine bridge interface %s"), br_name);
        goto cleanup;
    }

    /* if_xml is the new interface to define.
     */
    if (!(if_handle = virInterfaceDefineXML(ctl->conn, (char *) if_xml, 0))) {
        vshError(ctl, _("Failed to define new interface %s"), if_name);
        goto cleanup;
    }

    vshPrint(ctl, _("Device %s un-attached from bridge %s\n"),
             if_name, br_name);

    /* unless requested otherwise, undefine the bridge device */
    if (!nostart) {
        if (virInterfaceCreate(if_handle, 0) < 0) {
            vshError(ctl, _("Failed to start interface %s"), if_name);
            goto cleanup;
        }
        vshPrint(ctl, _("Interface %s started\n"), if_name);
    }

    ret = true;
 cleanup:
    if (if_handle)
       virInterfaceFree(if_handle);
    if (br_handle)
       virInterfaceFree(br_handle);
    VIR_FREE(if_xml);
    VIR_FREE(br_xml);
    VIR_FREE(if_type);
    VIR_FREE(if_name);
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml_doc);
    return ret;
}

9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999
/*
 * "nwfilter-define" command
 */
static const vshCmdInfo info_nwfilter_define[] = {
    {"help", N_("define or update a network filter from an XML file")},
    {"desc", N_("Define a new network filter or update an existing one.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_nwfilter_define[] = {
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing an XML network filter description")},
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
10000
static bool
10001 10002 10003
cmdNWFilterDefine(vshControl *ctl, const vshCmd *cmd)
{
    virNWFilterPtr nwfilter;
10004
    const char *from = NULL;
E
Eric Blake 已提交
10005
    bool ret = true;
10006 10007
    char *buffer;

10008
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
10009
        return false;
10010

10011
    if (vshCommandOptString(cmd, "file", &from) <= 0)
E
Eric Blake 已提交
10012
        return false;
10013 10014

    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
E
Eric Blake 已提交
10015
        return false;
10016 10017 10018 10019 10020 10021 10022 10023 10024 10025

    nwfilter = virNWFilterDefineXML(ctl->conn, buffer);
    VIR_FREE(buffer);

    if (nwfilter != NULL) {
        vshPrint(ctl, _("Network filter %s defined from %s\n"),
                 virNWFilterGetName(nwfilter), from);
        virNWFilterFree(nwfilter);
    } else {
        vshError(ctl, _("Failed to define network filter from %s"), from);
E
Eric Blake 已提交
10026
        ret = false;
10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045
    }
    return ret;
}


/*
 * "nwfilter-undefine" command
 */
static const vshCmdInfo info_nwfilter_undefine[] = {
    {"help", N_("undefine a network filter")},
    {"desc", N_("Undefine a given network filter.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_nwfilter_undefine[] = {
    {"nwfilter", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network filter name or uuid")},
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
10046
static bool
10047 10048 10049
cmdNWFilterUndefine(vshControl *ctl, const vshCmd *cmd)
{
    virNWFilterPtr nwfilter;
E
Eric Blake 已提交
10050
    bool ret = true;
10051
    const char *name;
10052

10053
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
10054
        return false;
10055 10056

    if (!(nwfilter = vshCommandOptNWFilter(ctl, cmd, &name)))
E
Eric Blake 已提交
10057
        return false;
10058 10059 10060 10061 10062

    if (virNWFilterUndefine(nwfilter) == 0) {
        vshPrint(ctl, _("Network filter %s undefined\n"), name);
    } else {
        vshError(ctl, _("Failed to undefine network filter %s"), name);
E
Eric Blake 已提交
10063
        ret = false;
10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084
    }

    virNWFilterFree(nwfilter);
    return ret;
}


/*
 * "nwfilter-dumpxml" command
 */
static const vshCmdInfo info_nwfilter_dumpxml[] = {
    {"help", N_("network filter information in XML")},
    {"desc", N_("Output the network filter information as an XML dump to stdout.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_nwfilter_dumpxml[] = {
    {"nwfilter", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network filter name or uuid")},
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
10085
static bool
10086 10087 10088
cmdNWFilterDumpXML(vshControl *ctl, const vshCmd *cmd)
{
    virNWFilterPtr nwfilter;
E
Eric Blake 已提交
10089
    bool ret = true;
10090 10091
    char *dump;

10092
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
10093
        return false;
10094 10095

    if (!(nwfilter = vshCommandOptNWFilter(ctl, cmd, NULL)))
E
Eric Blake 已提交
10096
        return false;
10097 10098 10099

    dump = virNWFilterGetXMLDesc(nwfilter, 0);
    if (dump != NULL) {
10100
        vshPrint(ctl, "%s", dump);
10101 10102
        VIR_FREE(dump);
    } else {
E
Eric Blake 已提交
10103
        ret = false;
10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122
    }

    virNWFilterFree(nwfilter);
    return ret;
}

/*
 * "nwfilter-list" command
 */
static const vshCmdInfo info_nwfilter_list[] = {
    {"help", N_("list network filters")},
    {"desc", N_("Returns list of network filters.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_nwfilter_list[] = {
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
10123
static bool
10124 10125 10126 10127 10128 10129
cmdNWFilterList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    int numfilters, i;
    char **names;
    char uuid[VIR_UUID_STRING_BUFLEN];

10130
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
10131
        return false;
10132 10133 10134 10135

    numfilters = virConnectNumOfNWFilters(ctl->conn);
    if (numfilters < 0) {
        vshError(ctl, "%s", _("Failed to list network filters"));
E
Eric Blake 已提交
10136
        return false;
10137 10138 10139 10140 10141 10142 10143 10144
    }

    names = vshMalloc(ctl, sizeof(char *) * numfilters);

    if ((numfilters = virConnectListNWFilters(ctl->conn, names,
                                              numfilters)) < 0) {
        vshError(ctl, "%s", _("Failed to list network filters"));
        VIR_FREE(names);
E
Eric Blake 已提交
10145
        return false;
10146 10147
    }

10148
    qsort(&names[0], numfilters, sizeof(char *), vshNameSorter);
10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172

    vshPrintExtra(ctl, "%-36s  %-20s \n", _("UUID"), _("Name"));
    vshPrintExtra(ctl,
       "----------------------------------------------------------------\n");

    for (i = 0; i < numfilters; i++) {
        virNWFilterPtr nwfilter =
            virNWFilterLookupByName(ctl->conn, names[i]);

        /* this kind of work with networks is not atomic operation */
        if (!nwfilter) {
            VIR_FREE(names[i]);
            continue;
        }

        virNWFilterGetUUIDString(nwfilter, uuid);
        vshPrint(ctl, "%-36s  %-20s\n",
                 uuid,
                 virNWFilterGetName(nwfilter));
        virNWFilterFree(nwfilter);
        VIR_FREE(names[i]);
    }

    VIR_FREE(names);
E
Eric Blake 已提交
10173
    return true;
10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190
}


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

static const vshCmdOptDef opts_nwfilter_edit[] = {
    {"nwfilter", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network filter name or uuid")},
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
10191
static bool
10192
cmdNWFilterEdit(vshControl *ctl, const vshCmd *cmd)
10193
{
E
Eric Blake 已提交
10194
    bool ret = false;
10195
    virNWFilterPtr nwfilter = NULL;
10196
    virNWFilterPtr nwfilter_edited = NULL;
10197

10198
    if (!vshConnectionUsability(ctl, ctl->conn))
10199 10200
        goto cleanup;

10201
    nwfilter = vshCommandOptNWFilter(ctl, cmd, NULL);
10202 10203 10204
    if (nwfilter == NULL)
        goto cleanup;

W
Wen Congyang 已提交
10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216
#define EDIT_GET_XML virNWFilterGetXMLDesc(nwfilter, 0)
#define EDIT_NOT_CHANGED \
    vshPrint(ctl, _("Network filter %s XML "            \
                    "configuration not changed.\n"),    \
             virNWFilterGetName(nwfilter));             \
    ret = true; goto edit_cleanup;
#define EDIT_DEFINE \
    (nwfilter_edited = virNWFilterDefineXML(ctl->conn, doc_edited))
#define EDIT_FREE \
    if (nwfilter_edited)    \
        virNWFilterFree(nwfilter);
#include "virsh-edit.c"
10217

10218
    vshPrint(ctl, _("Network filter %s XML configuration edited.\n"),
10219
             virNWFilterGetName(nwfilter_edited));
10220

E
Eric Blake 已提交
10221
    ret = true;
10222 10223 10224

cleanup:
    if (nwfilter)
10225 10226 10227
        virNWFilterFree(nwfilter);
    if (nwfilter_edited)
        virNWFilterFree(nwfilter_edited);
10228 10229 10230 10231 10232

    return ret;
}


10233
/**************************************************************************/
10234
/*
10235
 * "pool-autostart" command
10236
 */
10237
static const vshCmdInfo info_pool_autostart[] = {
10238
    {"help", N_("autostart a pool")},
10239
    {"desc",
10240
     N_("Configure a pool to be automatically started at boot.")},
10241
    {NULL, NULL}
10242 10243
};

10244
static const vshCmdOptDef opts_pool_autostart[] = {
10245 10246
    {"pool",  VSH_OT_DATA, VSH_OFLAG_REQ, N_("pool name or uuid")},
    {"disable", VSH_OT_BOOL, 0, N_("disable autostarting")},
10247 10248
    {NULL, 0, 0, NULL}
};
10249

E
Eric Blake 已提交
10250
static bool
10251
cmdPoolAutostart(vshControl *ctl, const vshCmd *cmd)
10252
{
10253
    virStoragePoolPtr pool;
10254
    const char *name;
10255
    int autostart;
10256

10257
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
10258
        return false;
10259

10260
    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", &name)))
E
Eric Blake 已提交
10261
        return false;
10262

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

10265 10266
    if (virStoragePoolSetAutostart(pool, autostart) < 0) {
        if (autostart)
10267
            vshError(ctl, _("failed to mark pool %s as autostarted"), name);
10268
        else
10269
            vshError(ctl, _("failed to unmark pool %s as autostarted"), name);
10270
        virStoragePoolFree(pool);
E
Eric Blake 已提交
10271
        return false;
10272 10273
    }

10274
    if (autostart)
10275
        vshPrint(ctl, _("Pool %s marked as autostarted\n"), name);
10276
    else
10277
        vshPrint(ctl, _("Pool %s unmarked as autostarted\n"), name);
10278

L
Laine Stump 已提交
10279
    virStoragePoolFree(pool);
E
Eric Blake 已提交
10280
    return true;
10281 10282
}

10283
/*
10284
 * "pool-create" command
10285
 */
10286
static const vshCmdInfo info_pool_create[] = {
10287 10288
    {"help", N_("create a pool from an XML file")},
    {"desc", N_("Create a pool.")},
10289 10290 10291
    {NULL, NULL}
};

10292
static const vshCmdOptDef opts_pool_create[] = {
J
Jim Meyering 已提交
10293
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ,
10294
     N_("file containing an XML pool description")},
10295 10296 10297
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
10298
static bool
10299
cmdPoolCreate(vshControl *ctl, const vshCmd *cmd)
10300
{
10301
    virStoragePoolPtr pool;
10302
    const char *from = NULL;
E
Eric Blake 已提交
10303
    bool ret = true;
10304
    char *buffer;
10305

10306
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
10307
        return false;
10308

10309
    if (vshCommandOptString(cmd, "file", &from) <= 0)
E
Eric Blake 已提交
10310
        return false;
10311

10312
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
E
Eric Blake 已提交
10313
        return false;
10314

10315
    pool = virStoragePoolCreateXML(ctl->conn, buffer, 0);
10316
    VIR_FREE(buffer);
10317 10318 10319 10320

    if (pool != NULL) {
        vshPrint(ctl, _("Pool %s created from %s\n"),
                 virStoragePoolGetName(pool), from);
L
Laine Stump 已提交
10321
        virStoragePoolFree(pool);
10322
    } else {
10323
        vshError(ctl, _("Failed to create pool from %s"), from);
E
Eric Blake 已提交
10324
        ret = false;
10325 10326
    }
    return ret;
10327 10328
}

10329

10330 10331 10332 10333
/*
 * "nodedev-create" command
 */
static const vshCmdInfo info_node_device_create[] = {
10334
    {"help", N_("create a device defined "
10335
                          "by an XML file on the node")},
10336
    {"desc", N_("Create a device on the node.  Note that this "
10337 10338 10339 10340 10341 10342 10343
                          "command creates devices on the physical host "
                          "that can then be assigned to a virtual machine.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_node_device_create[] = {
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ,
10344
     N_("file containing an XML description of the device")},
10345 10346 10347
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
10348
static bool
10349 10350 10351
cmdNodeDeviceCreate(vshControl *ctl, const vshCmd *cmd)
{
    virNodeDevicePtr dev = NULL;
10352
    const char *from = NULL;
E
Eric Blake 已提交
10353
    bool ret = true;
10354 10355
    char *buffer;

10356
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
10357
        return false;
10358

10359
    if (vshCommandOptString(cmd, "file", &from) <= 0)
E
Eric Blake 已提交
10360
        return false;
10361

10362
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
E
Eric Blake 已提交
10363
        return false;
10364 10365

    dev = virNodeDeviceCreateXML(ctl->conn, buffer, 0);
10366
    VIR_FREE(buffer);
10367 10368 10369 10370

    if (dev != NULL) {
        vshPrint(ctl, _("Node device %s created from %s\n"),
                 virNodeDeviceGetName(dev), from);
L
Laine Stump 已提交
10371
        virNodeDeviceFree(dev);
10372
    } else {
10373
        vshError(ctl, _("Failed to create node device from %s"), from);
E
Eric Blake 已提交
10374
        ret = false;
10375 10376 10377 10378 10379 10380 10381 10382 10383 10384
    }

    return ret;
}


/*
 * "nodedev-destroy" command
 */
static const vshCmdInfo info_node_device_destroy[] = {
10385
    {"help", N_("destroy (stop) a device on the node")},
10386
    {"desc", N_("Destroy a device on the node.  Note that this "
10387
                "command destroys devices on the physical host")},
10388 10389 10390 10391 10392
    {NULL, NULL}
};

static const vshCmdOptDef opts_node_device_destroy[] = {
    {"name", VSH_OT_DATA, VSH_OFLAG_REQ,
10393
     N_("name of the device to be destroyed")},
10394 10395 10396
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
10397
static bool
10398 10399 10400
cmdNodeDeviceDestroy(vshControl *ctl, const vshCmd *cmd)
{
    virNodeDevicePtr dev = NULL;
E
Eric Blake 已提交
10401
    bool ret = true;
10402
    const char *name = NULL;
10403

10404
    if (!vshConnectionUsability(ctl, ctl->conn)) {
E
Eric Blake 已提交
10405
        return false;
10406 10407
    }

10408
    if (vshCommandOptString(cmd, "name", &name) <= 0)
E
Eric Blake 已提交
10409
        return false;
10410 10411 10412 10413 10414 10415

    dev = virNodeDeviceLookupByName(ctl->conn, name);

    if (virNodeDeviceDestroy(dev) == 0) {
        vshPrint(ctl, _("Destroyed node device '%s'\n"), name);
    } else {
10416
        vshError(ctl, _("Failed to destroy node device '%s'"), name);
E
Eric Blake 已提交
10417
        ret = false;
10418 10419 10420 10421 10422 10423 10424
    }

    virNodeDeviceFree(dev);
    return ret;
}


10425
/*
10426
 * XML Building helper for pool-define-as and pool-create-as
10427
 */
10428
static const vshCmdOptDef opts_pool_X_as[] = {
10429 10430 10431 10432 10433 10434 10435 10436
    {"name", VSH_OT_DATA, VSH_OFLAG_REQ, N_("name of the pool")},
    {"print-xml", VSH_OT_BOOL, 0, N_("print XML document, but don't define/create")},
    {"type", VSH_OT_DATA, VSH_OFLAG_REQ, N_("type of the pool")},
    {"source-host", VSH_OT_DATA, 0, N_("source-host for underlying storage")},
    {"source-path", VSH_OT_DATA, 0, N_("source path for underlying storage")},
    {"source-dev", VSH_OT_DATA, 0, N_("source device for underlying storage")},
    {"source-name", VSH_OT_DATA, 0, N_("source name for underlying storage")},
    {"target", VSH_OT_DATA, 0, N_("target for underlying storage")},
10437
    {"source-format", VSH_OT_STRING, 0, N_("format for underlying storage")},
10438 10439 10440
    {NULL, 0, 0, NULL}
};

10441
static int buildPoolXML(const vshCmd *cmd, const char **retname, char **xml) {
10442

10443 10444
    const char *name = NULL, *type = NULL, *srcHost = NULL, *srcPath = NULL,
               *srcDev = NULL, *srcName = NULL, *srcFormat = NULL, *target = NULL;
10445
    virBuffer buf = VIR_BUFFER_INITIALIZER;
10446

10447
    if (vshCommandOptString(cmd, "name", &name) <= 0)
10448
        goto cleanup;
10449
    if (vshCommandOptString(cmd, "type", &type) <= 0)
10450 10451
        goto cleanup;

10452 10453 10454 10455 10456
    if (vshCommandOptString(cmd, "source-host", &srcHost) < 0 ||
        vshCommandOptString(cmd, "source-path", &srcPath) < 0 ||
        vshCommandOptString(cmd, "source-dev", &srcDev) < 0 ||
        vshCommandOptString(cmd, "source-name", &srcName) < 0 ||
        vshCommandOptString(cmd, "source-format", &srcFormat) < 0 ||
10457 10458
        vshCommandOptString(cmd, "target", &target) < 0) {
        vshError(NULL, "%s", _("missing argument"));
10459
        goto cleanup;
10460
    }
10461

10462 10463
    virBufferAsprintf(&buf, "<pool type='%s'>\n", type);
    virBufferAsprintf(&buf, "  <name>%s</name>\n", name);
10464
    if (srcHost || srcPath || srcDev || srcFormat || srcName) {
10465
        virBufferAddLit(&buf, "  <source>\n");
10466

10467
        if (srcHost)
10468
            virBufferAsprintf(&buf, "    <host name='%s'/>\n", srcHost);
10469
        if (srcPath)
10470
            virBufferAsprintf(&buf, "    <dir path='%s'/>\n", srcPath);
10471
        if (srcDev)
10472
            virBufferAsprintf(&buf, "    <device path='%s'/>\n", srcDev);
10473
        if (srcFormat)
10474
            virBufferAsprintf(&buf, "    <format type='%s'/>\n", srcFormat);
10475
        if (srcName)
10476
            virBufferAsprintf(&buf, "    <name>%s</name>\n", srcName);
10477 10478

        virBufferAddLit(&buf, "  </source>\n");
10479 10480
    }
    if (target) {
10481
        virBufferAddLit(&buf, "  <target>\n");
10482
        virBufferAsprintf(&buf, "    <path>%s</path>\n", target);
10483
        virBufferAddLit(&buf, "  </target>\n");
10484
    }
10485 10486 10487 10488
    virBufferAddLit(&buf, "</pool>\n");

    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
E
Eric Blake 已提交
10489
        return false;
10490
    }
10491 10492 10493

    *xml = virBufferContentAndReset(&buf);
    *retname = name;
E
Eric Blake 已提交
10494
    return true;
10495 10496

cleanup:
10497
    virBufferFreeAndReset(&buf);
E
Eric Blake 已提交
10498
    return false;
10499 10500 10501 10502 10503 10504
}

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

E
Eric Blake 已提交
10510
static bool
10511 10512 10513
cmdPoolCreateAs(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool;
10514 10515
    const char *name;
    char *xml;
10516
    bool printXML = vshCommandOptBool(cmd, "print-xml");
10517

10518
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
10519
        return false;
10520 10521

    if (!buildPoolXML(cmd, &name, &xml))
E
Eric Blake 已提交
10522
        return false;
10523

10524
    if (printXML) {
10525
        vshPrint(ctl, "%s", xml);
10526
        VIR_FREE(xml);
10527
    } else {
10528
        pool = virStoragePoolCreateXML(ctl->conn, xml, 0);
10529
        VIR_FREE(xml);
10530

10531 10532 10533 10534
        if (pool != NULL) {
            vshPrint(ctl, _("Pool %s created\n"), name);
            virStoragePoolFree(pool);
        } else {
10535
            vshError(ctl, _("Failed to create pool %s"), name);
E
Eric Blake 已提交
10536
            return false;
10537 10538
        }
    }
E
Eric Blake 已提交
10539
    return true;
10540 10541
}

10542

10543
/*
10544
 * "pool-define" command
10545
 */
10546
static const vshCmdInfo info_pool_define[] = {
10547 10548
    {"help", N_("define (but don't start) a pool from an XML file")},
    {"desc", N_("Define a pool.")},
10549 10550 10551
    {NULL, NULL}
};

10552
static const vshCmdOptDef opts_pool_define[] = {
10553
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing an XML pool description")},
10554 10555 10556
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
10557
static bool
10558
cmdPoolDefine(vshControl *ctl, const vshCmd *cmd)
10559
{
10560
    virStoragePoolPtr pool;
10561
    const char *from = NULL;
E
Eric Blake 已提交
10562
    bool ret = true;
10563
    char *buffer;
10564

10565
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
10566
        return false;
10567

10568
    if (vshCommandOptString(cmd, "file", &from) <= 0)
E
Eric Blake 已提交
10569
        return false;
10570

10571
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
E
Eric Blake 已提交
10572
        return false;
10573

10574
    pool = virStoragePoolDefineXML(ctl->conn, buffer, 0);
10575
    VIR_FREE(buffer);
10576 10577 10578 10579

    if (pool != NULL) {
        vshPrint(ctl, _("Pool %s defined from %s\n"),
                 virStoragePoolGetName(pool), from);
L
Laine Stump 已提交
10580
        virStoragePoolFree(pool);
10581
    } else {
10582
        vshError(ctl, _("Failed to define pool from %s"), from);
E
Eric Blake 已提交
10583
        ret = false;
10584 10585
    }
    return ret;
10586 10587
}

10588

10589 10590 10591
/*
 * "pool-define-as" command
 */
10592
static const vshCmdInfo info_pool_define_as[] = {
10593 10594
    {"help", N_("define a pool from a set of args")},
    {"desc", N_("Define a pool.")},
10595 10596 10597
    {NULL, NULL}
};

E
Eric Blake 已提交
10598
static bool
10599
cmdPoolDefineAs(vshControl *ctl, const vshCmd *cmd)
10600 10601
{
    virStoragePoolPtr pool;
10602 10603
    const char *name;
    char *xml;
10604
    bool printXML = vshCommandOptBool(cmd, "print-xml");
10605

10606
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
10607
        return false;
10608

10609
    if (!buildPoolXML(cmd, &name, &xml))
E
Eric Blake 已提交
10610
        return false;
10611

10612
    if (printXML) {
10613
        vshPrint(ctl, "%s", xml);
10614
        VIR_FREE(xml);
10615
    } else {
10616
        pool = virStoragePoolDefineXML(ctl->conn, xml, 0);
10617
        VIR_FREE(xml);
10618

10619 10620 10621 10622
        if (pool != NULL) {
            vshPrint(ctl, _("Pool %s defined\n"), name);
            virStoragePoolFree(pool);
        } else {
10623
            vshError(ctl, _("Failed to define pool %s"), name);
E
Eric Blake 已提交
10624
            return false;
10625 10626
        }
    }
E
Eric Blake 已提交
10627
    return true;
10628 10629 10630
}


10631
/*
10632
 * "pool-build" command
10633
 */
10634
static const vshCmdInfo info_pool_build[] = {
10635 10636
    {"help", N_("build a pool")},
    {"desc", N_("Build a given pool.")},
10637 10638 10639
    {NULL, NULL}
};

10640
static const vshCmdOptDef opts_pool_build[] = {
10641
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, N_("pool name or uuid")},
10642 10643
    {"no-overwrite", VSH_OT_BOOL, 0, N_("do not overwrite an existing pool of this type")},
    {"overwrite", VSH_OT_BOOL, 0, N_("overwrite any existing data")},
10644 10645 10646
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
10647
static bool
10648
cmdPoolBuild(vshControl *ctl, const vshCmd *cmd)
10649
{
10650
    virStoragePoolPtr pool;
E
Eric Blake 已提交
10651
    bool ret = true;
10652
    const char *name;
10653
    unsigned int flags = 0;
10654

10655
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
10656
        return false;
10657

10658
    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", &name)))
E
Eric Blake 已提交
10659
        return false;
10660

E
Eric Blake 已提交
10661
    if (vshCommandOptBool(cmd, "no-overwrite")) {
10662 10663 10664
        flags |= VIR_STORAGE_POOL_BUILD_NO_OVERWRITE;
    }

E
Eric Blake 已提交
10665
    if (vshCommandOptBool(cmd, "overwrite")) {
10666 10667 10668 10669
        flags |= VIR_STORAGE_POOL_BUILD_OVERWRITE;
    }

    if (virStoragePoolBuild(pool, flags) == 0) {
10670
        vshPrint(ctl, _("Pool %s built\n"), name);
10671
    } else {
10672
        vshError(ctl, _("Failed to build pool %s"), name);
E
Eric Blake 已提交
10673
        ret = false;
10674 10675
    }

10676 10677
    virStoragePoolFree(pool);

10678 10679 10680
    return ret;
}

10681
/*
10682
 * "pool-destroy" command
10683
 */
10684
static const vshCmdInfo info_pool_destroy[] = {
10685 10686 10687
    {"help", N_("destroy (stop) a pool")},
    {"desc",
     N_("Forcefully stop a given pool. Raw data in the pool is untouched")},
10688 10689 10690
    {NULL, NULL}
};

10691
static const vshCmdOptDef opts_pool_destroy[] = {
10692
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, N_("pool name or uuid")},
10693 10694 10695
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
10696
static bool
10697
cmdPoolDestroy(vshControl *ctl, const vshCmd *cmd)
10698
{
10699
    virStoragePoolPtr pool;
E
Eric Blake 已提交
10700
    bool ret = true;
10701
    const char *name;
10702

10703
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
10704
        return false;
10705

10706
    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", &name)))
E
Eric Blake 已提交
10707
        return false;
10708

10709 10710 10711
    if (virStoragePoolDestroy(pool) == 0) {
        vshPrint(ctl, _("Pool %s destroyed\n"), name);
    } else {
10712
        vshError(ctl, _("Failed to destroy pool %s"), name);
E
Eric Blake 已提交
10713
        ret = false;
10714 10715
    }

10716
    virStoragePoolFree(pool);
10717 10718 10719
    return ret;
}

10720

10721
/*
10722 10723
 * "pool-delete" command
 */
10724
static const vshCmdInfo info_pool_delete[] = {
10725 10726
    {"help", N_("delete a pool")},
    {"desc", N_("Delete a given pool.")},
10727 10728 10729
    {NULL, NULL}
};

10730
static const vshCmdOptDef opts_pool_delete[] = {
10731
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, N_("pool name or uuid")},
10732 10733 10734
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
10735
static bool
10736
cmdPoolDelete(vshControl *ctl, const vshCmd *cmd)
10737 10738
{
    virStoragePoolPtr pool;
E
Eric Blake 已提交
10739
    bool ret = true;
10740
    const char *name;
10741

10742
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
10743
        return false;
10744 10745

    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", &name)))
E
Eric Blake 已提交
10746
        return false;
10747 10748

    if (virStoragePoolDelete(pool, 0) == 0) {
D
Daniel Veillard 已提交
10749
        vshPrint(ctl, _("Pool %s deleted\n"), name);
10750
    } else {
10751
        vshError(ctl, _("Failed to delete pool %s"), name);
E
Eric Blake 已提交
10752
        ret = false;
10753 10754
    }

L
Laine Stump 已提交
10755
    virStoragePoolFree(pool);
10756 10757 10758 10759 10760 10761 10762
    return ret;
}


/*
 * "pool-refresh" command
 */
10763
static const vshCmdInfo info_pool_refresh[] = {
10764 10765
    {"help", N_("refresh a pool")},
    {"desc", N_("Refresh a given pool.")},
10766 10767 10768
    {NULL, NULL}
};

10769
static const vshCmdOptDef opts_pool_refresh[] = {
10770
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, N_("pool name or uuid")},
10771 10772 10773
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
10774
static bool
10775
cmdPoolRefresh(vshControl *ctl, const vshCmd *cmd)
10776 10777
{
    virStoragePoolPtr pool;
E
Eric Blake 已提交
10778
    bool ret = true;
10779
    const char *name;
10780

10781
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
10782
        return false;
10783 10784

    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", &name)))
E
Eric Blake 已提交
10785
        return false;
10786 10787 10788 10789

    if (virStoragePoolRefresh(pool, 0) == 0) {
        vshPrint(ctl, _("Pool %s refreshed\n"), name);
    } else {
10790
        vshError(ctl, _("Failed to refresh pool %s"), name);
E
Eric Blake 已提交
10791
        ret = false;
10792 10793 10794 10795 10796 10797 10798 10799 10800 10801
    }
    virStoragePoolFree(pool);

    return ret;
}


/*
 * "pool-dumpxml" command
 */
10802
static const vshCmdInfo info_pool_dumpxml[] = {
10803 10804
    {"help", N_("pool information in XML")},
    {"desc", N_("Output the pool information as an XML dump to stdout.")},
10805 10806 10807
    {NULL, NULL}
};

10808
static const vshCmdOptDef opts_pool_dumpxml[] = {
10809
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, N_("pool name or uuid")},
10810
    {"inactive", VSH_OT_BOOL, 0, N_("show inactive defined XML")},
10811 10812 10813
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
10814
static bool
10815
cmdPoolDumpXML(vshControl *ctl, const vshCmd *cmd)
10816 10817
{
    virStoragePoolPtr pool;
E
Eric Blake 已提交
10818
    bool ret = true;
10819 10820
    bool inactive = vshCommandOptBool(cmd, "inactive");
    unsigned int flags = 0;
10821 10822
    char *dump;

10823 10824 10825
    if (inactive)
        flags |= VIR_STORAGE_XML_INACTIVE;

10826
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
10827
        return false;
10828 10829

    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", NULL)))
E
Eric Blake 已提交
10830
        return false;
10831

10832
    dump = virStoragePoolGetXMLDesc(pool, flags);
10833
    if (dump != NULL) {
10834
        vshPrint(ctl, "%s", dump);
10835
        VIR_FREE(dump);
10836
    } else {
E
Eric Blake 已提交
10837
        ret = false;
10838 10839 10840 10841 10842 10843 10844 10845 10846 10847
    }

    virStoragePoolFree(pool);
    return ret;
}


/*
 * "pool-list" command
 */
10848
static const vshCmdInfo info_pool_list[] = {
10849 10850
    {"help", N_("list pools")},
    {"desc", N_("Returns list of pools.")},
10851 10852 10853
    {NULL, NULL}
};

10854
static const vshCmdOptDef opts_pool_list[] = {
10855 10856
    {"inactive", VSH_OT_BOOL, 0, N_("list inactive pools")},
    {"all", VSH_OT_BOOL, 0, N_("list inactive & active pools")},
10857
    {"details", VSH_OT_BOOL, 0, N_("display extended details for pools")},
10858 10859 10860
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
10861
static bool
10862
cmdPoolList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
10863
{
10864 10865
    virStoragePoolInfo info;
    char **poolNames = NULL;
W
Wen Congyang 已提交
10866 10867
    int i, ret;
    bool functionReturn;
10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883
    int numActivePools = 0, numInactivePools = 0, numAllPools = 0;
    size_t stringLength = 0, nameStrLength = 0;
    size_t autostartStrLength = 0, persistStrLength = 0;
    size_t stateStrLength = 0, capStrLength = 0;
    size_t allocStrLength = 0, availStrLength = 0;
    struct poolInfoText {
        char *state;
        char *autostart;
        char *persistent;
        char *capacity;
        char *allocation;
        char *available;
    };
    struct poolInfoText *poolInfoTexts = NULL;

    /* Determine the options passed by the user */
10884 10885 10886 10887
    bool all = vshCommandOptBool(cmd, "all");
    bool details = vshCommandOptBool(cmd, "details");
    bool inactive = vshCommandOptBool(cmd, "inactive");
    bool active = !inactive || all;
10888 10889
    inactive |= all;

10890
    /* Check the connection to libvirtd daemon is still working */
10891
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
10892
        return false;
10893

10894
    /* Retrieve the number of active storage pools */
10895
    if (active) {
10896 10897
        numActivePools = virConnectNumOfStoragePools(ctl->conn);
        if (numActivePools < 0) {
10898
            vshError(ctl, "%s", _("Failed to list active pools"));
E
Eric Blake 已提交
10899
            return false;
10900 10901
        }
    }
10902 10903

    /* Retrieve the number of inactive storage pools */
10904
    if (inactive) {
10905 10906
        numInactivePools = virConnectNumOfDefinedStoragePools(ctl->conn);
        if (numInactivePools < 0) {
10907
            vshError(ctl, "%s", _("Failed to list inactive pools"));
E
Eric Blake 已提交
10908
            return false;
10909
        }
10910
    }
10911

10912 10913
    /* Determine the total number of pools to list */
    numAllPools = numActivePools + numInactivePools;
10914

10915 10916 10917 10918 10919 10920 10921
    /* Allocate memory for arrays of storage pool names and info */
    poolNames = vshCalloc(ctl, numAllPools, sizeof(*poolNames));
    poolInfoTexts =
        vshCalloc(ctl, numAllPools, sizeof(*poolInfoTexts));

    /* Retrieve a list of active storage pool names */
    if (active) {
E
Eric Blake 已提交
10922 10923
        if (virConnectListStoragePools(ctl->conn,
                                       poolNames, numActivePools) < 0) {
10924 10925 10926
            vshError(ctl, "%s", _("Failed to list active pools"));
            VIR_FREE(poolInfoTexts);
            VIR_FREE(poolNames);
E
Eric Blake 已提交
10927
            return false;
10928 10929 10930
        }
    }

10931 10932
    /* Add the inactive storage pools to the end of the name list */
    if (inactive) {
E
Eric Blake 已提交
10933 10934 10935
        if (virConnectListDefinedStoragePools(ctl->conn,
                                              &poolNames[numActivePools],
                                              numInactivePools) < 0) {
10936 10937 10938
            vshError(ctl, "%s", _("Failed to list inactive pools"));
            VIR_FREE(poolInfoTexts);
            VIR_FREE(poolNames);
E
Eric Blake 已提交
10939
            return false;
10940 10941
        }
    }
10942

10943
    /* Sort the storage pool names */
10944
    qsort(poolNames, numAllPools, sizeof(*poolNames), vshNameSorter);
10945 10946 10947 10948 10949 10950 10951 10952

    /* Collect the storage pool information for display */
    for (i = 0; i < numAllPools; i++) {
        int autostart = 0, persistent = 0;

        /* Retrieve a pool object, looking it up by name */
        virStoragePoolPtr pool = virStoragePoolLookupByName(ctl->conn,
                                                            poolNames[i]);
10953
        if (!pool) {
10954
            VIR_FREE(poolNames[i]);
10955 10956 10957
            continue;
        }

10958
        /* Retrieve the autostart status of the pool */
10959
        if (virStoragePoolGetAutostart(pool, &autostart) < 0)
10960
            poolInfoTexts[i].autostart = vshStrdup(ctl, _("no autostart"));
10961
        else
10962 10963 10964 10965 10966 10967
            poolInfoTexts[i].autostart = vshStrdup(ctl, autostart ?
                                                    _("yes") : _("no"));

        /* Retrieve the persistence status of the pool */
        if (details) {
            persistent = virStoragePoolIsPersistent(pool);
10968 10969
            vshDebug(ctl, VSH_ERR_DEBUG, "Persistent flag value: %d\n",
                     persistent);
10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980
            if (persistent < 0)
                poolInfoTexts[i].persistent = vshStrdup(ctl, _("unknown"));
            else
                poolInfoTexts[i].persistent = vshStrdup(ctl, persistent ?
                                                         _("yes") : _("no"));

            /* Keep the length of persistent string if longest so far */
            stringLength = strlen(poolInfoTexts[i].persistent);
            if (stringLength > persistStrLength)
                persistStrLength = stringLength;
        }
10981

10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093
        /* Collect further extended information about the pool */
        if (virStoragePoolGetInfo(pool, &info) != 0) {
            /* Something went wrong retrieving pool info, cope with it */
            vshError(ctl, "%s", _("Could not retrieve pool information"));
            poolInfoTexts[i].state = vshStrdup(ctl, _("unknown"));
            if (details) {
                poolInfoTexts[i].capacity = vshStrdup(ctl, _("unknown"));
                poolInfoTexts[i].allocation = vshStrdup(ctl, _("unknown"));
                poolInfoTexts[i].available = vshStrdup(ctl, _("unknown"));
            }
        } else {
            /* Decide which state string to display */
            if (details) {
                /* --details option was specified, we're using detailed state
                 * strings */
                switch (info.state) {
                case VIR_STORAGE_POOL_INACTIVE:
                    poolInfoTexts[i].state = vshStrdup(ctl, _("inactive"));
                    break;
                case VIR_STORAGE_POOL_BUILDING:
                    poolInfoTexts[i].state = vshStrdup(ctl, _("building"));
                    break;
                case VIR_STORAGE_POOL_RUNNING:
                    poolInfoTexts[i].state = vshStrdup(ctl, _("running"));
                    break;
                case VIR_STORAGE_POOL_DEGRADED:
                    poolInfoTexts[i].state = vshStrdup(ctl, _("degraded"));
                    break;
                case VIR_STORAGE_POOL_INACCESSIBLE:
                    poolInfoTexts[i].state = vshStrdup(ctl, _("inaccessible"));
                    break;
                }

                /* Create the pool size related strings */
                if (info.state == VIR_STORAGE_POOL_RUNNING ||
                    info.state == VIR_STORAGE_POOL_DEGRADED) {
                    double val;
                    const char *unit;

                    /* Create the capacity output string */
                    val = prettyCapacity(info.capacity, &unit);
                    ret = virAsprintf(&poolInfoTexts[i].capacity,
                                      "%.2lf %s", val, unit);
                    if (ret < 0) {
                        /* An error occurred creating the string, return */
                        goto asprintf_failure;
                    }

                    /* Create the allocation output string */
                    val = prettyCapacity(info.allocation, &unit);
                    ret = virAsprintf(&poolInfoTexts[i].allocation,
                                      "%.2lf %s", val, unit);
                    if (ret < 0) {
                        /* An error occurred creating the string, return */
                        goto asprintf_failure;
                    }

                    /* Create the available space output string */
                    val = prettyCapacity(info.available, &unit);
                    ret = virAsprintf(&poolInfoTexts[i].available,
                                      "%.2lf %s", val, unit);
                    if (ret < 0) {
                        /* An error occurred creating the string, return */
                        goto asprintf_failure;
                    }
                } else {
                    /* Capacity related information isn't available */
                    poolInfoTexts[i].capacity = vshStrdup(ctl, _("-"));
                    poolInfoTexts[i].allocation = vshStrdup(ctl, _("-"));
                    poolInfoTexts[i].available = vshStrdup(ctl, _("-"));
                }

                /* Keep the length of capacity string if longest so far */
                stringLength = strlen(poolInfoTexts[i].capacity);
                if (stringLength > capStrLength)
                    capStrLength = stringLength;

                /* Keep the length of allocation string if longest so far */
                stringLength = strlen(poolInfoTexts[i].allocation);
                if (stringLength > allocStrLength)
                    allocStrLength = stringLength;

                /* Keep the length of available string if longest so far */
                stringLength = strlen(poolInfoTexts[i].available);
                if (stringLength > availStrLength)
                    availStrLength = stringLength;
            } else {
                /* --details option was not specified, only active/inactive
                * state strings are used */
                if (info.state == VIR_STORAGE_POOL_INACTIVE)
                    poolInfoTexts[i].state = vshStrdup(ctl, _("inactive"));
                else
                    poolInfoTexts[i].state = vshStrdup(ctl, _("active"));
            }
        }

        /* Keep the length of name string if longest so far */
        stringLength = strlen(poolNames[i]);
        if (stringLength > nameStrLength)
            nameStrLength = stringLength;

        /* Keep the length of state string if longest so far */
        stringLength = strlen(poolInfoTexts[i].state);
        if (stringLength > stateStrLength)
            stateStrLength = stringLength;

        /* Keep the length of autostart string if longest so far */
        stringLength = strlen(poolInfoTexts[i].autostart);
        if (stringLength > autostartStrLength)
            autostartStrLength = stringLength;

        /* Free the pool object */
11094 11095 11096
        virStoragePoolFree(pool);
    }

11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114
    /* If the --details option wasn't selected, we output the pool
     * info using the fixed string format from previous versions to
     * maintain backward compatibility.
     */

    /* Output basic info then return if --details option not selected */
    if (!details) {
        /* Output old style header */
        vshPrintExtra(ctl, "%-20s %-10s %-10s\n", _("Name"), _("State"),
                      _("Autostart"));
        vshPrintExtra(ctl, "-----------------------------------------\n");

        /* Output old style pool info */
        for (i = 0; i < numAllPools; i++) {
            vshPrint(ctl, "%-20s %-10s %-10s\n",
                 poolNames[i],
                 poolInfoTexts[i].state,
                 poolInfoTexts[i].autostart);
11115 11116
        }

11117
        /* Cleanup and return */
E
Eric Blake 已提交
11118
        functionReturn = true;
11119 11120
        goto cleanup;
    }
11121

11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159
    /* We only get here if the --details option was selected. */

    /* Use the length of name header string if it's longest */
    stringLength = strlen(_("Name"));
    if (stringLength > nameStrLength)
        nameStrLength = stringLength;

    /* Use the length of state header string if it's longest */
    stringLength = strlen(_("State"));
    if (stringLength > stateStrLength)
        stateStrLength = stringLength;

    /* Use the length of autostart header string if it's longest */
    stringLength = strlen(_("Autostart"));
    if (stringLength > autostartStrLength)
        autostartStrLength = stringLength;

    /* Use the length of persistent header string if it's longest */
    stringLength = strlen(_("Persistent"));
    if (stringLength > persistStrLength)
        persistStrLength = stringLength;

    /* Use the length of capacity header string if it's longest */
    stringLength = strlen(_("Capacity"));
    if (stringLength > capStrLength)
        capStrLength = stringLength;

    /* Use the length of allocation header string if it's longest */
    stringLength = strlen(_("Allocation"));
    if (stringLength > allocStrLength)
        allocStrLength = stringLength;

    /* Use the length of available header string if it's longest */
    stringLength = strlen(_("Available"));
    if (stringLength > availStrLength)
        availStrLength = stringLength;

    /* Display the string lengths for debugging. */
11160
    vshDebug(ctl, VSH_ERR_DEBUG, "Longest name string = %lu chars\n",
11161
             (unsigned long) nameStrLength);
11162
    vshDebug(ctl, VSH_ERR_DEBUG, "Longest state string = %lu chars\n",
11163
             (unsigned long) stateStrLength);
11164
    vshDebug(ctl, VSH_ERR_DEBUG, "Longest autostart string = %lu chars\n",
11165
             (unsigned long) autostartStrLength);
11166
    vshDebug(ctl, VSH_ERR_DEBUG, "Longest persistent string = %lu chars\n",
11167
             (unsigned long) persistStrLength);
11168
    vshDebug(ctl, VSH_ERR_DEBUG, "Longest capacity string = %lu chars\n",
11169
             (unsigned long) capStrLength);
11170
    vshDebug(ctl, VSH_ERR_DEBUG, "Longest allocation string = %lu chars\n",
11171
             (unsigned long) allocStrLength);
11172
    vshDebug(ctl, VSH_ERR_DEBUG, "Longest available string = %lu chars\n",
11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215
             (unsigned long) availStrLength);

    /* Create the output template.  Each column is sized according to
     * the longest string.
     */
    char *outputStr;
    ret = virAsprintf(&outputStr,
              "%%-%lus  %%-%lus  %%-%lus  %%-%lus  %%%lus  %%%lus  %%%lus\n",
              (unsigned long) nameStrLength,
              (unsigned long) stateStrLength,
              (unsigned long) autostartStrLength,
              (unsigned long) persistStrLength,
              (unsigned long) capStrLength,
              (unsigned long) allocStrLength,
              (unsigned long) availStrLength);
    if (ret < 0) {
        /* An error occurred creating the string, return */
        goto asprintf_failure;
    }

    /* Display the header */
    vshPrint(ctl, outputStr, _("Name"), _("State"), _("Autostart"),
             _("Persistent"), _("Capacity"), _("Allocation"), _("Available"));
    for (i = nameStrLength + stateStrLength + autostartStrLength
                           + persistStrLength + capStrLength
                           + allocStrLength + availStrLength
                           + 12; i > 0; i--)
        vshPrintExtra(ctl, "-");
    vshPrintExtra(ctl, "\n");

    /* Display the pool info rows */
    for (i = 0; i < numAllPools; i++) {
        vshPrint(ctl, outputStr,
                 poolNames[i],
                 poolInfoTexts[i].state,
                 poolInfoTexts[i].autostart,
                 poolInfoTexts[i].persistent,
                 poolInfoTexts[i].capacity,
                 poolInfoTexts[i].allocation,
                 poolInfoTexts[i].available);
    }

    /* Cleanup and return */
E
Eric Blake 已提交
11216
    functionReturn = true;
11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230
    goto cleanup;

asprintf_failure:

    /* Display an appropriate error message then cleanup and return */
    switch (errno) {
    case ENOMEM:
        /* Couldn't allocate memory */
        vshError(ctl, "%s", _("Out of memory"));
        break;
    default:
        /* Some other error */
        vshError(ctl, _("virAsprintf failed (errno %d)"), errno);
    }
E
Eric Blake 已提交
11231
    functionReturn = false;
11232

11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244
cleanup:

    /* Safely free the memory allocated in this function */
    for (i = 0; i < numAllPools; i++) {
        /* Cleanup the memory for one pool info structure */
        VIR_FREE(poolInfoTexts[i].state);
        VIR_FREE(poolInfoTexts[i].autostart);
        VIR_FREE(poolInfoTexts[i].persistent);
        VIR_FREE(poolInfoTexts[i].capacity);
        VIR_FREE(poolInfoTexts[i].allocation);
        VIR_FREE(poolInfoTexts[i].available);
        VIR_FREE(poolNames[i]);
11245
    }
11246 11247 11248 11249 11250 11251 11252

    /* Cleanup the memory for the initial arrays*/
    VIR_FREE(poolInfoTexts);
    VIR_FREE(poolNames);

    /* Return the desired value */
    return functionReturn;
11253 11254
}

11255 11256 11257 11258
/*
 * "find-storage-pool-sources-as" command
 */
static const vshCmdInfo info_find_storage_pool_sources_as[] = {
11259 11260
    {"help", N_("find potential storage pool sources")},
    {"desc", N_("Returns XML <sources> document.")},
11261 11262 11263 11264 11265
    {NULL, NULL}
};

static const vshCmdOptDef opts_find_storage_pool_sources_as[] = {
    {"type", VSH_OT_DATA, VSH_OFLAG_REQ,
11266 11267 11268
     N_("type of storage pool sources to find")},
    {"host", VSH_OT_DATA, VSH_OFLAG_NONE, N_("optional host to query")},
    {"port", VSH_OT_DATA, VSH_OFLAG_NONE, N_("optional port to query")},
11269
    {"initiator", VSH_OT_DATA, VSH_OFLAG_NONE, N_("optional initiator IQN to use for query")},
11270 11271 11272
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
11273
static bool
11274 11275
cmdPoolDiscoverSourcesAs(vshControl * ctl, const vshCmd * cmd ATTRIBUTE_UNUSED)
{
11276
    const char *type = NULL, *host = NULL;
11277 11278
    char *srcSpec = NULL;
    char *srcList;
11279
    const char *initiator = NULL;
11280

11281 11282
    if (vshCommandOptString(cmd, "type", &type) <= 0 ||
        vshCommandOptString(cmd, "host", &host) < 0 ||
11283 11284
        vshCommandOptString(cmd, "initiator", &initiator) < 0) {
        vshError(ctl,"%s", _("missing argument"));
E
Eric Blake 已提交
11285
        return false;
11286
    }
11287

11288
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
11289
        return false;
11290 11291

    if (host) {
11292
        const char *port = NULL;
11293
        virBuffer buf = VIR_BUFFER_INITIALIZER;
11294 11295 11296 11297

        if (vshCommandOptString(cmd, "port", &port) < 0) {
            vshError(ctl, "%s", _("missing argument"));
            virBufferFreeAndReset(&buf);
E
Eric Blake 已提交
11298
            return false;
11299
        }
11300
        virBufferAddLit(&buf, "<source>\n");
11301
        virBufferAsprintf(&buf, "  <host name='%s'", host);
11302
        if (port)
11303
            virBufferAsprintf(&buf, " port='%s'", port);
11304
        virBufferAddLit(&buf, "/>\n");
11305 11306
        if (initiator) {
            virBufferAddLit(&buf, "  <initiator>\n");
11307
            virBufferAsprintf(&buf, "    <iqn name='%s'/>\n", initiator);
11308 11309
            virBufferAddLit(&buf, "  </initiator>\n");
        }
11310 11311 11312
        virBufferAddLit(&buf, "</source>\n");
        if (virBufferError(&buf)) {
            vshError(ctl, "%s", _("Out of memory"));
E
Eric Blake 已提交
11313
            return false;
11314
        }
11315
        srcSpec = virBufferContentAndReset(&buf);
11316 11317 11318
    }

    srcList = virConnectFindStoragePoolSources(ctl->conn, type, srcSpec, 0);
11319
    VIR_FREE(srcSpec);
11320
    if (srcList == NULL) {
11321
        vshError(ctl, _("Failed to find any %s pool sources"), type);
E
Eric Blake 已提交
11322
        return false;
11323 11324
    }
    vshPrint(ctl, "%s", srcList);
11325
    VIR_FREE(srcList);
11326

E
Eric Blake 已提交
11327
    return true;
11328 11329 11330 11331 11332 11333 11334
}


/*
 * "find-storage-pool-sources" command
 */
static const vshCmdInfo info_find_storage_pool_sources[] = {
11335 11336
    {"help", N_("discover potential storage pool sources")},
    {"desc", N_("Returns XML <sources> document.")},
11337 11338 11339 11340 11341
    {NULL, NULL}
};

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

E
Eric Blake 已提交
11348
static bool
11349 11350
cmdPoolDiscoverSources(vshControl * ctl, const vshCmd * cmd ATTRIBUTE_UNUSED)
{
11351
    const char *type = NULL, *srcSpecFile = NULL;
11352
    char *srcSpec = NULL, *srcList;
11353

11354
    if (vshCommandOptString(cmd, "type", &type) <= 0)
E
Eric Blake 已提交
11355
        return false;
11356

11357 11358
    if (vshCommandOptString(cmd, "srcSpec", &srcSpecFile) < 0) {
        vshError(ctl, "%s", _("missing option"));
E
Eric Blake 已提交
11359
        return false;
11360
    }
11361

11362
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
11363
        return false;
11364 11365

    if (srcSpecFile && virFileReadAll(srcSpecFile, VIRSH_MAX_XML_FILE, &srcSpec) < 0)
E
Eric Blake 已提交
11366
        return false;
11367 11368

    srcList = virConnectFindStoragePoolSources(ctl->conn, type, srcSpec, 0);
11369
    VIR_FREE(srcSpec);
11370
    if (srcList == NULL) {
11371
        vshError(ctl, _("Failed to find any %s pool sources"), type);
E
Eric Blake 已提交
11372
        return false;
11373 11374
    }
    vshPrint(ctl, "%s", srcList);
11375
    VIR_FREE(srcList);
11376

E
Eric Blake 已提交
11377
    return true;
11378 11379 11380
}


11381 11382 11383
/*
 * "pool-info" command
 */
11384
static const vshCmdInfo info_pool_info[] = {
11385 11386
    {"help", N_("storage pool information")},
    {"desc", N_("Returns basic information about the storage pool.")},
11387 11388 11389
    {NULL, NULL}
};

11390
static const vshCmdOptDef opts_pool_info[] = {
11391
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, N_("pool name or uuid")},
11392 11393 11394
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
11395
static bool
11396
cmdPoolInfo(vshControl *ctl, const vshCmd *cmd)
11397 11398 11399
{
    virStoragePoolInfo info;
    virStoragePoolPtr pool;
11400 11401
    int autostart = 0;
    int persistent = 0;
E
Eric Blake 已提交
11402
    bool ret = true;
11403 11404
    char uuid[VIR_UUID_STRING_BUFLEN];

11405
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
11406
        return false;
11407 11408

    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", NULL)))
E
Eric Blake 已提交
11409
        return false;
11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435

    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;
11436 11437 11438 11439
        case VIR_STORAGE_POOL_INACCESSIBLE:
            vshPrint(ctl, "%-15s %s\n", _("State:"),
                     _("inaccessible"));
            break;
11440 11441
        }

11442 11443
        /* Check and display whether the pool is persistent or not */
        persistent = virStoragePoolIsPersistent(pool);
11444 11445
        vshDebug(ctl, VSH_ERR_DEBUG, "Pool persistent flag value: %d\n",
                 persistent);
11446 11447 11448 11449 11450 11451 11452
        if (persistent < 0)
            vshPrint(ctl, "%-15s %s\n", _("Persistent:"),  _("unknown"));
        else
            vshPrint(ctl, "%-15s %s\n", _("Persistent:"), persistent ? _("yes") : _("no"));

        /* Check and display whether the pool is autostarted or not */
        virStoragePoolGetAutostart(pool, &autostart);
11453 11454
        vshDebug(ctl, VSH_ERR_DEBUG, "Pool autostart flag value: %d\n",
                 autostart);
11455 11456 11457 11458 11459
        if (autostart < 0)
            vshPrint(ctl, "%-15s %s\n", _("Autostart:"), _("no autostart"));
        else
            vshPrint(ctl, "%-15s %s\n", _("Autostart:"), autostart ? _("yes") : _("no"));

11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471
        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 {
E
Eric Blake 已提交
11472
        ret = false;
11473 11474 11475 11476 11477 11478 11479 11480 11481 11482
    }

    virStoragePoolFree(pool);
    return ret;
}


/*
 * "pool-name" command
 */
11483
static const vshCmdInfo info_pool_name[] = {
11484
    {"help", N_("convert a pool UUID to pool name")},
11485
    {"desc", ""},
11486 11487 11488
    {NULL, NULL}
};

11489
static const vshCmdOptDef opts_pool_name[] = {
11490
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, N_("pool uuid")},
11491 11492 11493
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
11494
static bool
11495
cmdPoolName(vshControl *ctl, const vshCmd *cmd)
11496 11497 11498
{
    virStoragePoolPtr pool;

11499
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
11500
        return false;
11501
    if (!(pool = vshCommandOptPoolBy(ctl, cmd, "pool", NULL,
11502
                                           VSH_BYUUID)))
E
Eric Blake 已提交
11503
        return false;
11504 11505 11506

    vshPrint(ctl, "%s\n", virStoragePoolGetName(pool));
    virStoragePoolFree(pool);
E
Eric Blake 已提交
11507
    return true;
11508 11509 11510 11511 11512 11513
}


/*
 * "pool-start" command
 */
11514
static const vshCmdInfo info_pool_start[] = {
11515 11516
    {"help", N_("start a (previously defined) inactive pool")},
    {"desc", N_("Start a pool.")},
11517 11518 11519
    {NULL, NULL}
};

11520
static const vshCmdOptDef opts_pool_start[] = {
11521
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, N_("name or uuid of the inactive pool")},
11522 11523 11524
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
11525
static bool
11526
cmdPoolStart(vshControl *ctl, const vshCmd *cmd)
11527 11528
{
    virStoragePoolPtr pool;
E
Eric Blake 已提交
11529
    bool ret = true;
11530
    const char *name = NULL;
11531

11532
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
11533
        return false;
11534

11535
    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", &name)))
E
Eric Blake 已提交
11536
         return false;
11537 11538

    if (virStoragePoolCreate(pool, 0) == 0) {
11539
        vshPrint(ctl, _("Pool %s started\n"), name);
11540
    } else {
11541
        vshError(ctl, _("Failed to start pool %s"), name);
E
Eric Blake 已提交
11542
        ret = false;
11543
    }
L
Laine Stump 已提交
11544 11545

    virStoragePoolFree(pool);
11546 11547 11548 11549
    return ret;
}


11550 11551 11552
/*
 * "vol-create-as" command
 */
11553
static const vshCmdInfo info_vol_create_as[] = {
11554 11555
    {"help", N_("create a volume from a set of args")},
    {"desc", N_("Create a vol.")},
11556 11557 11558
    {NULL, NULL}
};

11559
static const vshCmdOptDef opts_vol_create_as[] = {
11560 11561
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, N_("pool name")},
    {"name", VSH_OT_DATA, VSH_OFLAG_REQ, N_("name of the volume")},
E
Eric Blake 已提交
11562 11563 11564 11565 11566
    {"capacity", VSH_OT_DATA, VSH_OFLAG_REQ,
     N_("size of the vol, as scaled integer (default bytes)")},
    {"allocation", VSH_OT_STRING, 0,
     N_("initial allocation size, as scaled integer (default bytes)")},
    {"format", VSH_OT_STRING, 0,
11567
     N_("file format type raw,bochs,qcow,qcow2,qed,vmdk")},
E
Eric Blake 已提交
11568 11569 11570 11571
    {"backing-vol", VSH_OT_STRING, 0,
     N_("the backing volume if taking a snapshot")},
    {"backing-vol-format", VSH_OT_STRING, 0,
     N_("format of backing volume if taking a snapshot")},
11572 11573 11574
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
11575 11576
static int
vshVolSize(const char *data, unsigned long long *val)
11577 11578 11579 11580
{
    char *end;
    if (virStrToLong_ull(data, &end, 10, val) < 0)
        return -1;
E
Eric Blake 已提交
11581
    return virScaleInteger(val, end, 1, ULLONG_MAX);
11582 11583
}

E
Eric Blake 已提交
11584
static bool
11585
cmdVolCreateAs(vshControl *ctl, const vshCmd *cmd)
11586 11587 11588
{
    virStoragePoolPtr pool;
    virStorageVolPtr vol;
11589
    char *xml;
11590 11591
    const char *name, *capacityStr = NULL, *allocationStr = NULL, *format = NULL;
    const char *snapshotStrVol = NULL, *snapshotStrFormat = NULL;
11592
    unsigned long long capacity, allocation = 0;
11593
    virBuffer buf = VIR_BUFFER_INITIALIZER;
11594

11595
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
11596
        return false;
11597 11598 11599

    if (!(pool = vshCommandOptPoolBy(ctl, cmd, "pool", NULL,
                                     VSH_BYNAME)))
E
Eric Blake 已提交
11600
        return false;
11601

11602
    if (vshCommandOptString(cmd, "name", &name) <= 0)
11603 11604
        goto cleanup;

11605
    if (vshCommandOptString(cmd, "capacity", &capacityStr) <= 0)
11606
        goto cleanup;
11607 11608

    if (vshVolSize(capacityStr, &capacity) < 0) {
11609
        vshError(ctl, _("Malformed size %s"), capacityStr);
11610 11611
        goto cleanup;
    }
11612

E
Eric Blake 已提交
11613
    if (vshCommandOptString(cmd, "allocation", &allocationStr) > 0 &&
11614
        vshVolSize(allocationStr, &allocation) < 0) {
11615
        vshError(ctl, _("Malformed size %s"), allocationStr);
11616 11617
        goto cleanup;
    }
11618

11619 11620 11621 11622 11623
    if (vshCommandOptString(cmd, "format", &format) < 0 ||
        vshCommandOptString(cmd, "backing-vol", &snapshotStrVol) < 0 ||
        vshCommandOptString(cmd, "backing-vol-format",
                            &snapshotStrFormat) < 0) {
        vshError(ctl, "%s", _("missing argument"));
11624
        goto cleanup;
11625 11626
    }

11627

11628
    virBufferAddLit(&buf, "<volume>\n");
11629 11630
    virBufferAsprintf(&buf, "  <name>%s</name>\n", name);
    virBufferAsprintf(&buf, "  <capacity>%llu</capacity>\n", capacity);
11631
    if (allocationStr)
11632
        virBufferAsprintf(&buf, "  <allocation>%llu</allocation>\n", allocation);
11633 11634

    if (format) {
11635
        virBufferAddLit(&buf, "  <target>\n");
11636
        virBufferAsprintf(&buf, "    <format type='%s'/>\n",format);
11637
        virBufferAddLit(&buf, "  </target>\n");
11638
    }
11639

11640 11641 11642 11643
    /* Convert the snapshot parameters into backingStore XML */
    if (snapshotStrVol) {
        /* Lookup snapshot backing volume.  Try the backing-vol
         *  parameter as a name */
11644 11645
        vshDebug(ctl, VSH_ERR_DEBUG,
                 "%s: Look up backing store volume '%s' as name\n",
11646 11647 11648
                 cmd->def->name, snapshotStrVol);
        virStorageVolPtr snapVol = virStorageVolLookupByName(pool, snapshotStrVol);
        if (snapVol)
11649 11650
                vshDebug(ctl, VSH_ERR_DEBUG,
                         "%s: Backing store volume found using '%s' as name\n",
11651 11652 11653 11654 11655
                         cmd->def->name, snapshotStrVol);

        if (snapVol == NULL) {
            /* Snapshot backing volume not found by name.  Try the
             *  backing-vol parameter as a key */
11656 11657
            vshDebug(ctl, VSH_ERR_DEBUG,
                     "%s: Look up backing store volume '%s' as key\n",
11658 11659 11660
                     cmd->def->name, snapshotStrVol);
            snapVol = virStorageVolLookupByKey(ctl->conn, snapshotStrVol);
            if (snapVol)
11661 11662
                vshDebug(ctl, VSH_ERR_DEBUG,
                         "%s: Backing store volume found using '%s' as key\n",
11663 11664 11665 11666 11667
                         cmd->def->name, snapshotStrVol);
        }
        if (snapVol == NULL) {
            /* Snapshot backing volume not found by key.  Try the
             *  backing-vol parameter as a path */
11668 11669
            vshDebug(ctl, VSH_ERR_DEBUG,
                     "%s: Look up backing store volume '%s' as path\n",
11670 11671 11672
                     cmd->def->name, snapshotStrVol);
            snapVol = virStorageVolLookupByPath(ctl->conn, snapshotStrVol);
            if (snapVol)
11673 11674
                vshDebug(ctl, VSH_ERR_DEBUG,
                         "%s: Backing store volume found using '%s' as path\n",
11675 11676 11677 11678
                         cmd->def->name, snapshotStrVol);
        }
        if (snapVol == NULL) {
            vshError(ctl, _("failed to get vol '%s'"), snapshotStrVol);
11679
            goto cleanup;
11680 11681 11682 11683 11684
        }

        char *snapshotStrVolPath;
        if ((snapshotStrVolPath = virStorageVolGetPath(snapVol)) == NULL) {
            virStorageVolFree(snapVol);
11685
            goto cleanup;
11686 11687 11688 11689
        }

        /* Create XML for the backing store */
        virBufferAddLit(&buf, "  <backingStore>\n");
11690
        virBufferAsprintf(&buf, "    <path>%s</path>\n",snapshotStrVolPath);
11691
        if (snapshotStrFormat)
11692
            virBufferAsprintf(&buf, "    <format type='%s'/>\n",snapshotStrFormat);
11693 11694 11695 11696 11697 11698 11699 11700
        virBufferAddLit(&buf, "  </backingStore>\n");

        /* Cleanup snapshot allocations */
        VIR_FREE(snapshotStrVolPath);
        virStorageVolFree(snapVol);
    }

    virBufferAddLit(&buf, "</volume>\n");
11701

11702 11703
    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
11704
        goto cleanup;
11705 11706 11707
    }
    xml = virBufferContentAndReset(&buf);
    vol = virStorageVolCreateXML(pool, xml, 0);
11708
    VIR_FREE(xml);
11709 11710 11711 11712 11713
    virStoragePoolFree(pool);

    if (vol != NULL) {
        vshPrint(ctl, _("Vol %s created\n"), name);
        virStorageVolFree(vol);
E
Eric Blake 已提交
11714
        return true;
11715
    } else {
11716
        vshError(ctl, _("Failed to create vol %s"), name);
E
Eric Blake 已提交
11717
        return false;
11718 11719 11720
    }

 cleanup:
11721
    virBufferFreeAndReset(&buf);
11722
    virStoragePoolFree(pool);
E
Eric Blake 已提交
11723
    return false;
11724 11725 11726
}


11727 11728 11729
/*
 * "pool-undefine" command
 */
11730
static const vshCmdInfo info_pool_undefine[] = {
11731 11732
    {"help", N_("undefine an inactive pool")},
    {"desc", N_("Undefine the configuration for an inactive pool.")},
11733 11734 11735
    {NULL, NULL}
};

11736
static const vshCmdOptDef opts_pool_undefine[] = {
11737
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, N_("pool name or uuid")},
11738 11739 11740
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
11741
static bool
11742
cmdPoolUndefine(vshControl *ctl, const vshCmd *cmd)
11743 11744
{
    virStoragePoolPtr pool;
E
Eric Blake 已提交
11745
    bool ret = true;
11746
    const char *name;
11747

11748
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
11749
        return false;
11750 11751

    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", &name)))
E
Eric Blake 已提交
11752
        return false;
11753 11754 11755 11756

    if (virStoragePoolUndefine(pool) == 0) {
        vshPrint(ctl, _("Pool %s has been undefined\n"), name);
    } else {
11757
        vshError(ctl, _("Failed to undefine pool %s"), name);
E
Eric Blake 已提交
11758
        ret = false;
11759 11760
    }

L
Laine Stump 已提交
11761
    virStoragePoolFree(pool);
11762 11763 11764 11765 11766 11767 11768
    return ret;
}


/*
 * "pool-uuid" command
 */
11769
static const vshCmdInfo info_pool_uuid[] = {
11770
    {"help", N_("convert a pool name to pool UUID")},
11771
    {"desc", ""},
11772 11773 11774
    {NULL, NULL}
};

11775
static const vshCmdOptDef opts_pool_uuid[] = {
11776
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, N_("pool name")},
11777 11778 11779
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
11780
static bool
11781
cmdPoolUuid(vshControl *ctl, const vshCmd *cmd)
11782 11783 11784 11785
{
    virStoragePoolPtr pool;
    char uuid[VIR_UUID_STRING_BUFLEN];

11786
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
11787
        return false;
11788 11789

    if (!(pool = vshCommandOptPoolBy(ctl, cmd, "pool", NULL,
11790
                                           VSH_BYNAME)))
E
Eric Blake 已提交
11791
        return false;
11792 11793 11794 11795

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

L
Laine Stump 已提交
11798
    virStoragePoolFree(pool);
E
Eric Blake 已提交
11799
    return true;
11800 11801 11802 11803 11804 11805
}


/*
 * "vol-create" command
 */
11806
static const vshCmdInfo info_vol_create[] = {
11807 11808
    {"help", N_("create a vol from an XML file")},
    {"desc", N_("Create a vol.")},
11809 11810 11811
    {NULL, NULL}
};

11812
static const vshCmdOptDef opts_vol_create[] = {
11813 11814
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, N_("pool name")},
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing an XML vol description")},
11815 11816 11817
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
11818
static bool
11819
cmdVolCreate(vshControl *ctl, const vshCmd *cmd)
11820 11821 11822
{
    virStoragePoolPtr pool;
    virStorageVolPtr vol;
11823
    const char *from = NULL;
E
Eric Blake 已提交
11824
    bool ret = true;
11825 11826
    char *buffer;

11827
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
11828
        return false;
11829 11830

    if (!(pool = vshCommandOptPoolBy(ctl, cmd, "pool", NULL,
11831
                                           VSH_BYNAME)))
E
Eric Blake 已提交
11832
        return false;
11833

11834
    if (vshCommandOptString(cmd, "file", &from) <= 0) {
11835
        virStoragePoolFree(pool);
E
Eric Blake 已提交
11836
        return false;
11837 11838 11839
    }

    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) {
11840
        virshReportError(ctl);
11841
        virStoragePoolFree(pool);
E
Eric Blake 已提交
11842
        return false;
11843 11844 11845
    }

    vol = virStorageVolCreateXML(pool, buffer, 0);
11846
    VIR_FREE(buffer);
11847 11848 11849 11850 11851 11852 11853
    virStoragePoolFree(pool);

    if (vol != NULL) {
        vshPrint(ctl, _("Vol %s created from %s\n"),
                 virStorageVolGetName(vol), from);
        virStorageVolFree(vol);
    } else {
11854
        vshError(ctl, _("Failed to create vol from %s"), from);
E
Eric Blake 已提交
11855
        ret = false;
11856 11857 11858 11859
    }
    return ret;
}

11860 11861 11862 11863
/*
 * "vol-create-from" command
 */
static const vshCmdInfo info_vol_create_from[] = {
11864 11865
    {"help", N_("create a vol, using another volume as input")},
    {"desc", N_("Create a vol from an existing volume.")},
11866 11867 11868 11869
    {NULL, NULL}
};

static const vshCmdOptDef opts_vol_create_from[] = {
11870
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, N_("pool name or uuid")},
11871 11872
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing an XML vol description")},
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, N_("input vol name or key")},
E
Eric Blake 已提交
11873
    {"inputpool", VSH_OT_STRING, 0, N_("pool name or uuid of the input volume's pool")},
11874 11875 11876
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
11877
static bool
11878 11879 11880 11881
cmdVolCreateFrom(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool = NULL;
    virStorageVolPtr newvol = NULL, inputvol = NULL;
11882
    const char *from = NULL;
E
Eric Blake 已提交
11883
    bool ret = false;
11884 11885
    char *buffer = NULL;

11886
    if (!vshConnectionUsability(ctl, ctl->conn))
11887 11888
        goto cleanup;

11889
    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", NULL)))
11890 11891
        goto cleanup;

11892
    if (vshCommandOptString(cmd, "file", &from) <= 0) {
11893 11894 11895 11896 11897 11898 11899
        goto cleanup;
    }

    if (!(inputvol = vshCommandOptVol(ctl, cmd, "vol", "inputpool", NULL)))
        goto cleanup;

    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) {
11900
        virshReportError(ctl);
11901 11902 11903 11904 11905 11906 11907 11908 11909
        goto cleanup;
    }

    newvol = virStorageVolCreateXMLFrom(pool, buffer, inputvol, 0);

    if (newvol != NULL) {
        vshPrint(ctl, _("Vol %s created from input vol %s\n"),
                 virStorageVolGetName(newvol), virStorageVolGetName(inputvol));
    } else {
11910
        vshError(ctl, _("Failed to create vol from %s"), from);
11911 11912 11913
        goto cleanup;
    }

E
Eric Blake 已提交
11914
    ret = true;
11915
cleanup:
11916
    VIR_FREE(buffer);
11917 11918 11919 11920
    if (pool)
        virStoragePoolFree(pool);
    if (inputvol)
        virStorageVolFree(inputvol);
L
Laine Stump 已提交
11921 11922
    if (newvol)
        virStorageVolFree(newvol);
11923 11924 11925 11926
    return ret;
}

static xmlChar *
11927 11928
makeCloneXML(const char *origxml, const char *newname)
{
11929

11930 11931 11932
    xmlDocPtr doc = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlXPathObjectPtr obj = NULL;
11933 11934 11935
    xmlChar *newxml = NULL;
    int size;

11936
    doc = virXMLParseStringCtxt(origxml, _("(volume_definition)"), &ctxt);
11937 11938 11939 11940
    if (!doc)
        goto cleanup;

    obj = xmlXPathEval(BAD_CAST "/volume/name", ctxt);
E
Eric Blake 已提交
11941 11942
    if (obj == NULL || obj->nodesetval == NULL ||
        obj->nodesetval->nodeTab == NULL)
11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958
        goto cleanup;

    xmlNodeSetContent(obj->nodesetval->nodeTab[0], (const xmlChar *)newname);
    xmlDocDumpMemory(doc, &newxml, &size);

cleanup:
    xmlXPathFreeObject(obj);
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(doc);
    return newxml;
}

/*
 * "vol-clone" command
 */
static const vshCmdInfo info_vol_clone[] = {
11959 11960
    {"help", N_("clone a volume.")},
    {"desc", N_("Clone an existing volume.")},
11961 11962 11963 11964
    {NULL, NULL}
};

static const vshCmdOptDef opts_vol_clone[] = {
11965 11966
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, N_("orig vol name or key")},
    {"newname", VSH_OT_DATA, VSH_OFLAG_REQ, N_("clone name")},
E
Eric Blake 已提交
11967
    {"pool", VSH_OT_STRING, 0, N_("pool name or uuid")},
11968 11969 11970
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
11971
static bool
11972 11973 11974 11975
cmdVolClone(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr origpool = NULL;
    virStorageVolPtr origvol = NULL, newvol = NULL;
11976
    const char *name = NULL;
11977
    char *origxml = NULL;
11978
    xmlChar *newxml = NULL;
E
Eric Blake 已提交
11979
    bool ret = false;
11980

11981
    if (!vshConnectionUsability(ctl, ctl->conn))
11982 11983 11984 11985 11986 11987 11988
        goto cleanup;

    if (!(origvol = vshCommandOptVol(ctl, cmd, "vol", "pool", NULL)))
        goto cleanup;

    origpool = virStoragePoolLookupByVolume(origvol);
    if (!origpool) {
11989
        vshError(ctl, "%s", _("failed to get parent pool"));
11990 11991 11992
        goto cleanup;
    }

11993
    if (vshCommandOptString(cmd, "newname", &name) <= 0)
11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011
        goto cleanup;

    origxml = virStorageVolGetXMLDesc(origvol, 0);
    if (!origxml)
        goto cleanup;

    newxml = makeCloneXML(origxml, name);
    if (!newxml) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
        goto cleanup;
    }

    newvol = virStorageVolCreateXMLFrom(origpool, (char *) newxml, origvol, 0);

    if (newvol != NULL) {
        vshPrint(ctl, _("Vol %s cloned from %s\n"),
                 virStorageVolGetName(newvol), virStorageVolGetName(origvol));
    } else {
12012
        vshError(ctl, _("Failed to clone vol from %s"),
12013 12014 12015 12016
                 virStorageVolGetName(origvol));
        goto cleanup;
    }

E
Eric Blake 已提交
12017
    ret = true;
12018 12019

cleanup:
12020
    VIR_FREE(origxml);
12021 12022 12023
    xmlFree(newxml);
    if (origvol)
        virStorageVolFree(origvol);
L
Laine Stump 已提交
12024 12025
    if (newvol)
        virStorageVolFree(newvol);
12026 12027 12028 12029 12030
    if (origpool)
        virStoragePoolFree(origpool);
    return ret;
}

12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043

/*
 * "vol-upload" command
 */
static const vshCmdInfo info_vol_upload[] = {
    {"help", N_("upload a file into a volume")},
    {"desc", N_("Upload a file into a volume")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_vol_upload[] = {
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, N_("vol name, key or path")},
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file")},
E
Eric Blake 已提交
12044
    {"pool", VSH_OT_STRING, 0, N_("pool name or uuid")},
12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058
    {"offset", VSH_OT_INT, 0, N_("volume offset to upload to") },
    {"length", VSH_OT_INT, 0, N_("amount of data to upload") },
    {NULL, 0, 0, NULL}
};

static int
cmdVolUploadSource(virStreamPtr st ATTRIBUTE_UNUSED,
                   char *bytes, size_t nbytes, void *opaque)
{
    int *fd = opaque;

    return saferead(*fd, bytes, nbytes);
}

E
Eric Blake 已提交
12059
static bool
12060 12061 12062 12063
cmdVolUpload (vshControl *ctl, const vshCmd *cmd)
{
    const char *file = NULL;
    virStorageVolPtr vol = NULL;
E
Eric Blake 已提交
12064
    bool ret = false;
12065 12066 12067 12068 12069 12070 12071 12072 12073 12074
    int fd = -1;
    virStreamPtr st = NULL;
    const char *name = NULL;
    unsigned long long offset = 0, length = 0;

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

    if (vshCommandOptULongLong(cmd, "offset", &offset) < 0) {
        vshError(ctl, _("Unable to parse integer"));
E
Eric Blake 已提交
12075
        return false;
12076 12077 12078 12079
    }

    if (vshCommandOptULongLong(cmd, "length", &length) < 0) {
        vshError(ctl, _("Unable to parse integer"));
E
Eric Blake 已提交
12080
        return false;
12081 12082 12083
    }

    if (!(vol = vshCommandOptVol(ctl, cmd, "vol", "pool", &name))) {
E
Eric Blake 已提交
12084
        return false;
12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118
    }

    if (vshCommandOptString(cmd, "file", &file) < 0) {
        vshError(ctl, _("file must not be empty"));
        goto cleanup;
    }

    if ((fd = open(file, O_RDONLY)) < 0) {
        vshError(ctl, _("cannot read %s"), file);
        goto cleanup;
    }

    st = virStreamNew(ctl->conn, 0);
    if (virStorageVolUpload(vol, st, offset, length, 0) < 0) {
        vshError(ctl, _("cannot upload to volume %s"), name);
        goto cleanup;
    }

    if (virStreamSendAll(st, cmdVolUploadSource, &fd) < 0) {
        vshError(ctl, _("cannot send data to volume %s"), name);
        goto cleanup;
    }

    if (VIR_CLOSE(fd) < 0) {
        vshError(ctl, _("cannot close file %s"), file);
        virStreamAbort(st);
        goto cleanup;
    }

    if (virStreamFinish(st) < 0) {
        vshError(ctl, _("cannot close volume %s"), name);
        goto cleanup;
    }

E
Eric Blake 已提交
12119
    ret = true;
12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143

cleanup:
    if (vol)
        virStorageVolFree(vol);
    if (st)
        virStreamFree(st);
    VIR_FORCE_CLOSE(fd);
    return ret;
}



/*
 * "vol-download" command
 */
static const vshCmdInfo info_vol_download[] = {
    {"help", N_("Download a volume to a file")},
    {"desc", N_("Download a volume to a file")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_vol_download[] = {
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, N_("vol name, key or path")},
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file")},
E
Eric Blake 已提交
12144
    {"pool", VSH_OT_STRING, 0, N_("pool name or uuid")},
12145 12146 12147 12148 12149
    {"offset", VSH_OT_INT, 0, N_("volume offset to download from") },
    {"length", VSH_OT_INT, 0, N_("amount of data to download") },
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
12150
static bool
12151 12152 12153 12154
cmdVolDownload (vshControl *ctl, const vshCmd *cmd)
{
    const char *file = NULL;
    virStorageVolPtr vol = NULL;
E
Eric Blake 已提交
12155
    bool ret = false;
12156 12157 12158 12159
    int fd = -1;
    virStreamPtr st = NULL;
    const char *name = NULL;
    unsigned long long offset = 0, length = 0;
12160
    bool created = false;
12161 12162

    if (!vshConnectionUsability(ctl, ctl->conn))
12163
        return false;
12164 12165 12166

    if (vshCommandOptULongLong(cmd, "offset", &offset) < 0) {
        vshError(ctl, _("Unable to parse integer"));
E
Eric Blake 已提交
12167
        return false;
12168 12169 12170 12171
    }

    if (vshCommandOptULongLong(cmd, "length", &length) < 0) {
        vshError(ctl, _("Unable to parse integer"));
E
Eric Blake 已提交
12172
        return false;
12173 12174 12175
    }

    if (!(vol = vshCommandOptVol(ctl, cmd, "vol", "pool", &name)))
E
Eric Blake 已提交
12176
        return false;
12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188

    if (vshCommandOptString(cmd, "file", &file) < 0) {
        vshError(ctl, _("file must not be empty"));
        goto cleanup;
    }

    if ((fd = open(file, O_WRONLY|O_CREAT|O_EXCL, 0666)) < 0) {
        if (errno != EEXIST ||
            (fd = open(file, O_WRONLY|O_TRUNC, 0666)) < 0) {
            vshError(ctl, _("cannot create %s"), file);
            goto cleanup;
        }
12189 12190
    } else {
        created = true;
12191 12192 12193 12194 12195 12196 12197 12198
    }

    st = virStreamNew(ctl->conn, 0);
    if (virStorageVolDownload(vol, st, offset, length, 0) < 0) {
        vshError(ctl, _("cannot download from volume %s"), name);
        goto cleanup;
    }

12199
    if (virStreamRecvAll(st, vshStreamSink, &fd) < 0) {
12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214
        vshError(ctl, _("cannot receive data from volume %s"), name);
        goto cleanup;
    }

    if (VIR_CLOSE(fd) < 0) {
        vshError(ctl, _("cannot close file %s"), file);
        virStreamAbort(st);
        goto cleanup;
    }

    if (virStreamFinish(st) < 0) {
        vshError(ctl, _("cannot close volume %s"), name);
        goto cleanup;
    }

E
Eric Blake 已提交
12215
    ret = true;
12216 12217

cleanup:
12218
    VIR_FORCE_CLOSE(fd);
12219
    if (!ret && created)
12220 12221 12222 12223 12224 12225 12226 12227 12228
        unlink(file);
    if (vol)
        virStorageVolFree(vol);
    if (st)
        virStreamFree(st);
    return ret;
}


12229 12230 12231
/*
 * "vol-delete" command
 */
12232
static const vshCmdInfo info_vol_delete[] = {
12233 12234
    {"help", N_("delete a vol")},
    {"desc", N_("Delete a given vol.")},
12235 12236 12237
    {NULL, NULL}
};

12238
static const vshCmdOptDef opts_vol_delete[] = {
12239
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, N_("vol name, key or path")},
E
Eric Blake 已提交
12240
    {"pool", VSH_OT_STRING, 0, N_("pool name or uuid")},
12241 12242 12243
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
12244
static bool
12245
cmdVolDelete(vshControl *ctl, const vshCmd *cmd)
12246 12247
{
    virStorageVolPtr vol;
E
Eric Blake 已提交
12248
    bool ret = true;
12249
    const char *name;
12250

12251
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
12252
        return false;
12253 12254

    if (!(vol = vshCommandOptVol(ctl, cmd, "vol", "pool", &name))) {
E
Eric Blake 已提交
12255
        return false;
12256 12257 12258
    }

    if (virStorageVolDelete(vol, 0) == 0) {
D
Daniel Veillard 已提交
12259
        vshPrint(ctl, _("Vol %s deleted\n"), name);
12260
    } else {
12261
        vshError(ctl, _("Failed to delete vol %s"), name);
E
Eric Blake 已提交
12262
        ret = false;
12263 12264
    }

L
Laine Stump 已提交
12265
    virStorageVolFree(vol);
12266 12267 12268 12269
    return ret;
}


D
David Allan 已提交
12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280
/*
 * "vol-wipe" command
 */
static const vshCmdInfo info_vol_wipe[] = {
    {"help", N_("wipe a vol")},
    {"desc", N_("Ensure data previously on a volume is not accessible to future reads")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_vol_wipe[] = {
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, N_("vol name, key or path")},
E
Eric Blake 已提交
12281
    {"pool", VSH_OT_STRING, 0, N_("pool name or uuid")},
12282
    {"algorithm", VSH_OT_STRING, 0, N_("perform selected wiping algorithm")},
D
David Allan 已提交
12283 12284 12285
    {NULL, 0, 0, NULL}
};

12286 12287 12288 12289 12290
VIR_ENUM_DECL(virStorageVolWipeAlgorithm)
VIR_ENUM_IMPL(virStorageVolWipeAlgorithm, VIR_STORAGE_VOL_WIPE_ALG_LAST,
              "zero", "nnsa", "dod", "bsi", "gutmann", "schneier",
              "pfitzner7", "pfitzner33", "random");

E
Eric Blake 已提交
12291
static bool
D
David Allan 已提交
12292 12293 12294
cmdVolWipe(vshControl *ctl, const vshCmd *cmd)
{
    virStorageVolPtr vol;
12295
    bool ret = false;
12296
    const char *name;
12297 12298 12299
    const char *algorithm_str = NULL;
    int algorithm = VIR_STORAGE_VOL_WIPE_ALG_ZERO;
    int funcRet;
D
David Allan 已提交
12300

12301
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
12302
        return false;
D
David Allan 已提交
12303 12304

    if (!(vol = vshCommandOptVol(ctl, cmd, "vol", "pool", &name))) {
E
Eric Blake 已提交
12305
        return false;
D
David Allan 已提交
12306 12307
    }

12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325
    if (vshCommandOptString(cmd, "algorithm", &algorithm_str) < 0) {
        vshError(ctl, "%s", _("missing argument"));
        goto out;
    }

    if (algorithm_str &&
        (algorithm = virStorageVolWipeAlgorithmTypeFromString(algorithm_str)) < 0) {
        vshError(ctl, _("Unsupported algorithm '%s'"), algorithm_str);
        goto out;
    }

    if ((funcRet = virStorageVolWipePattern(vol, algorithm, 0)) < 0) {
        if (last_error->code == VIR_ERR_NO_SUPPORT &&
            algorithm == VIR_STORAGE_VOL_WIPE_ALG_ZERO)
            funcRet = virStorageVolWipe(vol, 0);
    }

    if (funcRet < 0) {
D
David Allan 已提交
12326
        vshError(ctl, _("Failed to wipe vol %s"), name);
12327
        goto out;
D
David Allan 已提交
12328 12329
    }

12330 12331 12332
    vshPrint(ctl, _("Vol %s wiped\n"), name);
    ret = true;
out:
D
David Allan 已提交
12333 12334 12335 12336 12337
    virStorageVolFree(vol);
    return ret;
}


12338 12339 12340
/*
 * "vol-info" command
 */
12341
static const vshCmdInfo info_vol_info[] = {
12342 12343
    {"help", N_("storage vol information")},
    {"desc", N_("Returns basic information about the storage vol.")},
12344 12345 12346
    {NULL, NULL}
};

12347
static const vshCmdOptDef opts_vol_info[] = {
12348
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, N_("vol name, key or path")},
E
Eric Blake 已提交
12349
    {"pool", VSH_OT_STRING, 0, N_("pool name or uuid")},
12350 12351 12352
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
12353
static bool
12354
cmdVolInfo(vshControl *ctl, const vshCmd *cmd)
12355 12356 12357
{
    virStorageVolInfo info;
    virStorageVolPtr vol;
E
Eric Blake 已提交
12358
    bool ret = true;
12359

12360
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
12361
        return false;
12362 12363

    if (!(vol = vshCommandOptVol(ctl, cmd, "vol", "pool", NULL)))
E
Eric Blake 已提交
12364
        return false;
12365 12366 12367 12368 12369 12370

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

    if (virStorageVolGetInfo(vol, &info) == 0) {
        double val;
        const char *unit;
R
Ryota Ozaki 已提交
12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383
        switch(info.type) {
        case VIR_STORAGE_VOL_FILE:
            vshPrint(ctl, "%-15s %s\n", _("Type:"), _("file"));
            break;

        case VIR_STORAGE_VOL_BLOCK:
            vshPrint(ctl, "%-15s %s\n", _("Type:"), _("block"));
            break;

        case VIR_STORAGE_VOL_DIR:
            vshPrint(ctl, "%-15s %s\n", _("Type:"), _("dir"));
            break;

12384 12385 12386 12387
        case VIR_STORAGE_VOL_NETWORK:
            vshPrint(ctl, "%-15s %s\n", _("Type:"), _("network"));
            break;

R
Ryota Ozaki 已提交
12388 12389 12390
        default:
            vshPrint(ctl, "%-15s %s\n", _("Type:"), _("unknown"));
        }
12391 12392 12393 12394 12395 12396 12397

        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 {
E
Eric Blake 已提交
12398
        ret = false;
12399 12400 12401 12402 12403 12404
    }

    virStorageVolFree(vol);
    return ret;
}

12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416
/*
 * "vol-resize" command
 */
static const vshCmdInfo info_vol_resize[] = {
    {"help", N_("resize a vol")},
    {"desc", N_("Resizes a storage volume.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_vol_resize[] = {
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, N_("vol name, key or path")},
    {"capacity", VSH_OT_DATA, VSH_OFLAG_REQ,
E
Eric Blake 已提交
12417
     N_("new capacity for the vol, as scaled integer (default bytes)")},
12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453
    {"pool", VSH_OT_STRING, 0, N_("pool name or uuid")},
    {"allocate", VSH_OT_BOOL, 0,
     N_("allocate the new capacity, rather than leaving it sparse")},
    {"delta", VSH_OT_BOOL, 0,
     N_("use capacity as a delta to current size, rather than the new size")},
    {"shrink", VSH_OT_BOOL, 0, N_("allow the resize to shrink the volume")},
    {NULL, 0, 0, NULL}
};

static bool
cmdVolResize(vshControl *ctl, const vshCmd *cmd)
{
    virStorageVolPtr vol;
    const char *capacityStr = NULL;
    unsigned long long capacity = 0;
    unsigned int flags = 0;
    bool ret = false;
    bool delta = false;

    if (vshCommandOptBool(cmd, "allocate"))
        flags |= VIR_STORAGE_VOL_RESIZE_ALLOCATE;
    if (vshCommandOptBool(cmd, "delta")) {
        delta = true;
        flags |= VIR_STORAGE_VOL_RESIZE_DELTA;
    }
    if (vshCommandOptBool(cmd, "shrink"))
        flags |= VIR_STORAGE_VOL_RESIZE_SHRINK;

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

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

    if (vshCommandOptString(cmd, "capacity", &capacityStr) <= 0)
        goto cleanup;
E
Eric Blake 已提交
12454 12455 12456 12457 12458 12459 12460 12461 12462
    virSkipSpaces(&capacityStr);
    if (*capacityStr == '-') {
        /* The API always requires a positive value; but we allow a
         * negative value for convenience.  */
        if (delta && vshCommandOptBool(cmd, "shrink")){
            capacityStr++;
        } else {
            vshError(ctl, "%s",
                     _("negative size requires --delta and --shrink"));
12463 12464 12465
            goto cleanup;
        }
    }
E
Eric Blake 已提交
12466 12467 12468 12469
    if (vshVolSize(capacityStr, &capacity) < 0) {
        vshError(ctl, _("Malformed size %s"), capacityStr);
        goto cleanup;
    }
12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489

    if (virStorageVolResize(vol, capacity, flags) == 0) {
        vshPrint(ctl,
                 delta ? _("Size of volume '%s' successfully changed by %s\n")
                 : _("Size of volume '%s' successfully changed to %s\n"),
                 virStorageVolGetName(vol), capacityStr);
        ret = true;
    } else {
        vshError(ctl,
                 delta ? _("Failed to change size of volume '%s' by %s\n")
                 : _("Failed to change size of volume '%s' to %s\n"),
                 virStorageVolGetName(vol), capacityStr);
        ret = false;
    }

cleanup:
    virStorageVolFree(vol);
    return ret;
}

12490 12491 12492 12493

/*
 * "vol-dumpxml" command
 */
12494
static const vshCmdInfo info_vol_dumpxml[] = {
12495 12496
    {"help", N_("vol information in XML")},
    {"desc", N_("Output the vol information as an XML dump to stdout.")},
12497 12498 12499
    {NULL, NULL}
};

12500
static const vshCmdOptDef opts_vol_dumpxml[] = {
12501
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, N_("vol name, key or path")},
E
Eric Blake 已提交
12502
    {"pool", VSH_OT_STRING, 0, N_("pool name or uuid")},
12503 12504 12505
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
12506
static bool
12507
cmdVolDumpXML(vshControl *ctl, const vshCmd *cmd)
12508 12509
{
    virStorageVolPtr vol;
E
Eric Blake 已提交
12510
    bool ret = true;
12511 12512
    char *dump;

12513
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
12514
        return false;
12515 12516

    if (!(vol = vshCommandOptVol(ctl, cmd, "vol", "pool", NULL)))
E
Eric Blake 已提交
12517
        return false;
12518 12519 12520

    dump = virStorageVolGetXMLDesc(vol, 0);
    if (dump != NULL) {
12521
        vshPrint(ctl, "%s", dump);
12522
        VIR_FREE(dump);
12523
    } else {
E
Eric Blake 已提交
12524
        ret = false;
12525 12526 12527 12528 12529 12530 12531 12532 12533 12534
    }

    virStorageVolFree(vol);
    return ret;
}


/*
 * "vol-list" command
 */
12535
static const vshCmdInfo info_vol_list[] = {
12536 12537
    {"help", N_("list vols")},
    {"desc", N_("Returns list of vols by pool.")},
12538 12539 12540
    {NULL, NULL}
};

12541
static const vshCmdOptDef opts_vol_list[] = {
12542
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, N_("pool name or uuid")},
12543
    {"details", VSH_OT_BOOL, 0, N_("display extended details for volumes")},
12544 12545 12546
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
12547
static bool
12548
cmdVolList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
12549
{
12550
    virStorageVolInfo volumeInfo;
12551 12552
    virStoragePoolPtr pool;
    char **activeNames = NULL;
12553 12554 12555
    char *outputStr = NULL;
    const char *unit;
    double val;
12556
    bool details = vshCommandOptBool(cmd, "details");
12557
    int numVolumes = 0, i;
W
Wen Congyang 已提交
12558 12559
    int ret;
    bool functionReturn;
12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570
    int stringLength = 0;
    size_t allocStrLength = 0, capStrLength = 0;
    size_t nameStrLength = 0, pathStrLength = 0;
    size_t typeStrLength = 0;
    struct volInfoText {
        char *allocation;
        char *capacity;
        char *path;
        char *type;
    };
    struct volInfoText *volInfoTexts = NULL;
12571

12572
    /* Check the connection to libvirtd daemon is still working */
12573
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
12574
        return false;
12575

12576
    /* Look up the pool information given to us by the user */
12577
    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", NULL)))
E
Eric Blake 已提交
12578
        return false;
12579

12580 12581
    /* Determine the number of volumes in the pool */
    numVolumes = virStoragePoolNumOfVolumes(pool);
12582

12583 12584 12585
    if (numVolumes < 0) {
        vshError(ctl, "%s", _("Failed to list storage volumes"));
        virStoragePoolFree(pool);
E
Eric Blake 已提交
12586
        return false;
12587 12588
    }

12589 12590 12591 12592 12593
    /* Retrieve the list of volume names in the pool */
    if (numVolumes > 0) {
        activeNames = vshCalloc(ctl, numVolumes, sizeof(*activeNames));
        if ((numVolumes = virStoragePoolListVolumes(pool, activeNames,
                                                    numVolumes)) < 0) {
12594
            vshError(ctl, "%s", _("Failed to list active vols"));
12595
            VIR_FREE(activeNames);
12596
            virStoragePoolFree(pool);
E
Eric Blake 已提交
12597
            return false;
12598 12599
        }

12600
        /* Sort the volume names */
12601
        qsort(&activeNames[0], numVolumes, sizeof(*activeNames), vshNameSorter);
12602 12603 12604

        /* Set aside memory for volume information pointers */
        volInfoTexts = vshCalloc(ctl, numVolumes, sizeof(*volInfoTexts));
12605 12606
    }

12607 12608 12609 12610 12611
    /* Collect the rest of the volume information for display */
    for (i = 0; i < numVolumes; i++) {
        /* Retrieve volume info */
        virStorageVolPtr vol = virStorageVolLookupByName(pool,
                                                         activeNames[i]);
12612

12613 12614 12615 12616
        /* Retrieve the volume path */
        if ((volInfoTexts[i].path = virStorageVolGetPath(vol)) == NULL) {
            /* Something went wrong retrieving a volume path, cope with it */
            volInfoTexts[i].path = vshStrdup(ctl, _("unknown"));
12617 12618
        }

12619 12620 12621 12622 12623 12624 12625 12626 12627
        /* If requested, retrieve volume type and sizing information */
        if (details) {
            if (virStorageVolGetInfo(vol, &volumeInfo) != 0) {
                /* Something went wrong retrieving volume info, cope with it */
                volInfoTexts[i].allocation = vshStrdup(ctl, _("unknown"));
                volInfoTexts[i].capacity = vshStrdup(ctl, _("unknown"));
                volInfoTexts[i].type = vshStrdup(ctl, _("unknown"));
            } else {
                /* Convert the returned volume info into output strings */
12628

12629
                /* Volume type */
12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642
                switch (volumeInfo.type) {
                        case VIR_STORAGE_VOL_FILE:
                            volInfoTexts[i].type = vshStrdup(ctl, _("file"));
                            break;
                        case VIR_STORAGE_VOL_BLOCK:
                            volInfoTexts[i].type = vshStrdup(ctl, _("block"));
                            break;
                        case VIR_STORAGE_VOL_DIR:
                            volInfoTexts[i].type = vshStrdup(ctl, _("dir"));
                            break;
                        default:
                            volInfoTexts[i].type = vshStrdup(ctl, _("unknown"));
                }
12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692

                /* Create the capacity output string */
                val = prettyCapacity(volumeInfo.capacity, &unit);
                ret = virAsprintf(&volInfoTexts[i].capacity,
                                  "%.2lf %s", val, unit);
                if (ret < 0) {
                    /* An error occurred creating the string, return */
                    goto asprintf_failure;
                }

                /* Create the allocation output string */
                val = prettyCapacity(volumeInfo.allocation, &unit);
                ret = virAsprintf(&volInfoTexts[i].allocation,
                                  "%.2lf %s", val, unit);
                if (ret < 0) {
                    /* An error occurred creating the string, return */
                    goto asprintf_failure;
                }
            }

            /* Remember the largest length for each output string.
             * This lets us displaying header and volume information rows
             * using a single, properly sized, printf style output string.
             */

            /* Keep the length of name string if longest so far */
            stringLength = strlen(activeNames[i]);
            if (stringLength > nameStrLength)
                nameStrLength = stringLength;

            /* Keep the length of path string if longest so far */
            stringLength = strlen(volInfoTexts[i].path);
            if (stringLength > pathStrLength)
                pathStrLength = stringLength;

            /* Keep the length of type string if longest so far */
            stringLength = strlen(volInfoTexts[i].type);
            if (stringLength > typeStrLength)
                typeStrLength = stringLength;

            /* Keep the length of capacity string if longest so far */
            stringLength = strlen(volInfoTexts[i].capacity);
            if (stringLength > capStrLength)
                capStrLength = stringLength;

            /* Keep the length of allocation string if longest so far */
            stringLength = strlen(volInfoTexts[i].allocation);
            if (stringLength > allocStrLength)
                allocStrLength = stringLength;
        }
12693

12694
        /* Cleanup memory allocation */
12695
        virStorageVolFree(vol);
12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713
    }

    /* If the --details option wasn't selected, we output the volume
     * info using the fixed string format from previous versions to
     * maintain backward compatibility.
     */

    /* Output basic info then return if --details option not selected */
    if (!details) {
        /* The old output format */
        vshPrintExtra(ctl, "%-20s %-40s\n", _("Name"), _("Path"));
        vshPrintExtra(ctl, "-----------------------------------------\n");
        for (i = 0; i < numVolumes; i++) {
            vshPrint(ctl, "%-20s %-40s\n", activeNames[i],
                     volInfoTexts[i].path);
        }

        /* Cleanup and return */
E
Eric Blake 已提交
12714
        functionReturn = true;
12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745
        goto cleanup;
    }

    /* We only get here if the --details option was selected. */

    /* Use the length of name header string if it's longest */
    stringLength = strlen(_("Name"));
    if (stringLength > nameStrLength)
        nameStrLength = stringLength;

    /* Use the length of path header string if it's longest */
    stringLength = strlen(_("Path"));
    if (stringLength > pathStrLength)
        pathStrLength = stringLength;

    /* Use the length of type header string if it's longest */
    stringLength = strlen(_("Type"));
    if (stringLength > typeStrLength)
        typeStrLength = stringLength;

    /* Use the length of capacity header string if it's longest */
    stringLength = strlen(_("Capacity"));
    if (stringLength > capStrLength)
        capStrLength = stringLength;

    /* Use the length of allocation header string if it's longest */
    stringLength = strlen(_("Allocation"));
    if (stringLength > allocStrLength)
        allocStrLength = stringLength;

    /* Display the string lengths for debugging */
12746 12747 12748 12749 12750 12751 12752 12753 12754 12755
    vshDebug(ctl, VSH_ERR_DEBUG,
             "Longest name string = %zu chars\n", nameStrLength);
    vshDebug(ctl, VSH_ERR_DEBUG,
             "Longest path string = %zu chars\n", pathStrLength);
    vshDebug(ctl, VSH_ERR_DEBUG,
             "Longest type string = %zu chars\n", typeStrLength);
    vshDebug(ctl, VSH_ERR_DEBUG,
             "Longest capacity string = %zu chars\n", capStrLength);
    vshDebug(ctl, VSH_ERR_DEBUG,
             "Longest allocation string = %zu chars\n", allocStrLength);
12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789

    /* Create the output template */
    ret = virAsprintf(&outputStr,
                      "%%-%lus  %%-%lus  %%-%lus  %%%lus  %%%lus\n",
                      (unsigned long) nameStrLength,
                      (unsigned long) pathStrLength,
                      (unsigned long) typeStrLength,
                      (unsigned long) capStrLength,
                      (unsigned long) allocStrLength);
    if (ret < 0) {
        /* An error occurred creating the string, return */
        goto asprintf_failure;
    }

    /* Display the header */
    vshPrint(ctl, outputStr, _("Name"), _("Path"), _("Type"),
             ("Capacity"), _("Allocation"));
    for (i = nameStrLength + pathStrLength + typeStrLength
                           + capStrLength + allocStrLength
                           + 8; i > 0; i--)
        vshPrintExtra(ctl, "-");
    vshPrintExtra(ctl, "\n");

    /* Display the volume info rows */
    for (i = 0; i < numVolumes; i++) {
        vshPrint(ctl, outputStr,
                 activeNames[i],
                 volInfoTexts[i].path,
                 volInfoTexts[i].type,
                 volInfoTexts[i].capacity,
                 volInfoTexts[i].allocation);
    }

    /* Cleanup and return */
E
Eric Blake 已提交
12790
    functionReturn = true;
12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804
    goto cleanup;

asprintf_failure:

    /* Display an appropriate error message then cleanup and return */
    switch (errno) {
    case ENOMEM:
        /* Couldn't allocate memory */
        vshError(ctl, "%s", _("Out of memory"));
        break;
    default:
        /* Some other error */
        vshError(ctl, _("virAsprintf failed (errno %d)"), errno);
    }
E
Eric Blake 已提交
12805
    functionReturn = false;
12806 12807 12808 12809 12810 12811 12812 12813 12814 12815

cleanup:

    /* Safely free the memory allocated in this function */
    for (i = 0; i < numVolumes; i++) {
        /* Cleanup the memory for one volume info structure per loop */
        VIR_FREE(volInfoTexts[i].path);
        VIR_FREE(volInfoTexts[i].type);
        VIR_FREE(volInfoTexts[i].capacity);
        VIR_FREE(volInfoTexts[i].allocation);
12816
        VIR_FREE(activeNames[i]);
12817
    }
12818 12819 12820 12821

    /* Cleanup remaining memory */
    VIR_FREE(outputStr);
    VIR_FREE(volInfoTexts);
12822
    VIR_FREE(activeNames);
12823
    virStoragePoolFree(pool);
12824 12825 12826

    /* Return the desired value */
    return functionReturn;
12827 12828 12829 12830 12831 12832
}


/*
 * "vol-name" command
 */
12833
static const vshCmdInfo info_vol_name[] = {
12834
    {"help", N_("returns the volume name for a given volume key or path")},
12835
    {"desc", ""},
12836 12837 12838
    {NULL, NULL}
};

12839
static const vshCmdOptDef opts_vol_name[] = {
12840
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, N_("volume key or path")},
12841 12842 12843
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
12844
static bool
12845
cmdVolName(vshControl *ctl, const vshCmd *cmd)
12846 12847 12848
{
    virStorageVolPtr vol;

12849
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
12850
        return false;
12851

12852
    if (!(vol = vshCommandOptVolBy(ctl, cmd, "vol", NULL, NULL,
12853
                                   VSH_BYUUID)))
E
Eric Blake 已提交
12854
        return false;
12855 12856 12857

    vshPrint(ctl, "%s\n", virStorageVolGetName(vol));
    virStorageVolFree(vol);
E
Eric Blake 已提交
12858
    return true;
12859 12860 12861
}


J
Justin Clift 已提交
12862 12863 12864 12865 12866 12867 12868 12869 12870 12871
/*
 * "vol-pool" command
 */
static const vshCmdInfo info_vol_pool[] = {
    {"help", N_("returns the storage pool for a given volume key or path")},
    {"desc", ""},
    {NULL, NULL}
};

static const vshCmdOptDef opts_vol_pool[] = {
12872
    {"uuid", VSH_OT_BOOL, 0, N_("return the pool uuid rather than pool name")},
J
Justin Clift 已提交
12873 12874 12875 12876
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, N_("volume key or path")},
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
12877
static bool
J
Justin Clift 已提交
12878 12879 12880 12881
cmdVolPool(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool;
    virStorageVolPtr vol;
12882
    char uuid[VIR_UUID_STRING_BUFLEN];
J
Justin Clift 已提交
12883 12884

    /* Check the connection to libvirtd daemon is still working */
12885
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
12886
        return false;
J
Justin Clift 已提交
12887 12888

    /* Use the supplied string to locate the volume */
12889
    if (!(vol = vshCommandOptVolBy(ctl, cmd, "vol", NULL, NULL,
J
Justin Clift 已提交
12890
                                   VSH_BYUUID))) {
E
Eric Blake 已提交
12891
        return false;
J
Justin Clift 已提交
12892 12893 12894 12895 12896 12897 12898
    }

    /* Look up the parent storage pool for the volume */
    pool = virStoragePoolLookupByVolume(vol);
    if (pool == NULL) {
        vshError(ctl, "%s", _("failed to get parent pool"));
        virStorageVolFree(vol);
E
Eric Blake 已提交
12899
        return false;
J
Justin Clift 已提交
12900 12901
    }

12902 12903 12904 12905 12906 12907 12908 12909 12910
    /* Return the requested details of the parent storage pool */
    if (vshCommandOptBool(cmd, "uuid")) {
        /* Retrieve and return pool UUID string */
        if (virStoragePoolGetUUIDString(pool, &uuid[0]) == 0)
            vshPrint(ctl, "%s\n", uuid);
    } else {
        /* Return the storage pool name */
        vshPrint(ctl, "%s\n", virStoragePoolGetName(pool));
    }
J
Justin Clift 已提交
12911 12912 12913 12914

    /* Cleanup */
    virStorageVolFree(vol);
    virStoragePoolFree(pool);
E
Eric Blake 已提交
12915
    return true;
J
Justin Clift 已提交
12916 12917
}

12918 12919 12920 12921

/*
 * "vol-key" command
 */
12922
static const vshCmdInfo info_vol_key[] = {
12923
    {"help", N_("returns the volume key for a given volume name or path")},
12924
    {"desc", ""},
12925 12926 12927
    {NULL, NULL}
};

12928
static const vshCmdOptDef opts_vol_key[] = {
12929
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, N_("volume name or path")},
E
Eric Blake 已提交
12930
    {"pool", VSH_OT_STRING, 0, N_("pool name or uuid")},
12931 12932 12933
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
12934
static bool
12935
cmdVolKey(vshControl *ctl, const vshCmd *cmd)
12936 12937 12938
{
    virStorageVolPtr vol;

12939
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
12940
        return false;
12941

12942
    if (!(vol = vshCommandOptVol(ctl, cmd, "vol", "pool", NULL)))
E
Eric Blake 已提交
12943
        return false;
12944 12945 12946

    vshPrint(ctl, "%s\n", virStorageVolGetKey(vol));
    virStorageVolFree(vol);
E
Eric Blake 已提交
12947
    return true;
12948 12949 12950 12951 12952 12953 12954
}



/*
 * "vol-path" command
 */
12955
static const vshCmdInfo info_vol_path[] = {
12956
    {"help", N_("returns the volume path for a given volume name or key")},
12957
    {"desc", ""},
12958 12959 12960
    {NULL, NULL}
};

12961
static const vshCmdOptDef opts_vol_path[] = {
12962
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, N_("volume name or key")},
E
Eric Blake 已提交
12963
    {"pool", VSH_OT_STRING, 0, N_("pool name or uuid")},
12964 12965 12966
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
12967
static bool
12968
cmdVolPath(vshControl *ctl, const vshCmd *cmd)
12969 12970
{
    virStorageVolPtr vol;
12971
    char * StorageVolPath;
12972

12973
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
12974
        return false;
12975

12976
    if (!(vol = vshCommandOptVol(ctl, cmd, "vol", "pool", NULL))) {
E
Eric Blake 已提交
12977
        return false;
12978
    }
12979

12980 12981 12982 12983 12984 12985 12986
    if ((StorageVolPath = virStorageVolGetPath(vol)) == NULL) {
        virStorageVolFree(vol);
        return false;
    }

    vshPrint(ctl, "%s\n", StorageVolPath);
    VIR_FREE(StorageVolPath);
12987
    virStorageVolFree(vol);
E
Eric Blake 已提交
12988
    return true;
12989 12990 12991
}


12992 12993 12994 12995
/*
 * "secret-define" command
 */
static const vshCmdInfo info_secret_define[] = {
12996 12997
    {"help", N_("define or modify a secret from an XML file")},
    {"desc", N_("Define or modify a secret.")},
12998 12999
    {NULL, NULL}
};
13000

13001
static const vshCmdOptDef opts_secret_define[] = {
13002
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing secret attributes in XML")},
13003 13004
    {NULL, 0, 0, NULL}
};
13005

E
Eric Blake 已提交
13006
static bool
13007 13008
cmdSecretDefine(vshControl *ctl, const vshCmd *cmd)
{
13009
    const char *from = NULL;
13010
    char *buffer;
13011
    virSecretPtr res;
13012
    char uuid[VIR_UUID_STRING_BUFLEN];
13013

13014
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
13015
        return false;
13016

13017
    if (vshCommandOptString(cmd, "file", &from) <= 0)
E
Eric Blake 已提交
13018
        return false;
13019 13020

    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
E
Eric Blake 已提交
13021
        return false;
13022 13023

    res = virSecretDefineXML(ctl->conn, buffer, 0);
13024
    VIR_FREE(buffer);
13025 13026

    if (res == NULL) {
13027
        vshError(ctl, _("Failed to set attributes from %s"), from);
E
Eric Blake 已提交
13028
        return false;
13029
    }
13030
    if (virSecretGetUUIDString(res, &(uuid[0])) < 0) {
13031
        vshError(ctl, "%s", _("Failed to get UUID of created secret"));
13032
        virSecretFree(res);
E
Eric Blake 已提交
13033
        return false;
13034 13035 13036
    }
    vshPrint(ctl, _("Secret %s created\n"), uuid);
    virSecretFree(res);
E
Eric Blake 已提交
13037
    return true;
13038 13039 13040 13041 13042 13043
}

/*
 * "secret-dumpxml" command
 */
static const vshCmdInfo info_secret_dumpxml[] = {
13044 13045
    {"help", N_("secret attributes in XML")},
    {"desc", N_("Output attributes of a secret as an XML dump to stdout.")},
13046 13047 13048 13049
    {NULL, NULL}
};

static const vshCmdOptDef opts_secret_dumpxml[] = {
13050
    {"secret", VSH_OT_DATA, VSH_OFLAG_REQ, N_("secret UUID")},
13051 13052 13053
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
13054
static bool
13055 13056 13057
cmdSecretDumpXML(vshControl *ctl, const vshCmd *cmd)
{
    virSecretPtr secret;
E
Eric Blake 已提交
13058
    bool ret = false;
13059 13060
    char *xml;

13061
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
13062
        return false;
13063 13064 13065

    secret = vshCommandOptSecret(ctl, cmd, NULL);
    if (secret == NULL)
E
Eric Blake 已提交
13066
        return false;
13067 13068 13069 13070

    xml = virSecretGetXMLDesc(secret, 0);
    if (xml == NULL)
        goto cleanup;
13071
    vshPrint(ctl, "%s", xml);
13072
    VIR_FREE(xml);
E
Eric Blake 已提交
13073
    ret = true;
13074 13075 13076 13077 13078 13079 13080 13081 13082 13083

cleanup:
    virSecretFree(secret);
    return ret;
}

/*
 * "secret-set-value" command
 */
static const vshCmdInfo info_secret_set_value[] = {
13084 13085
    {"help", N_("set a secret value")},
    {"desc", N_("Set a secret value.")},
13086 13087 13088 13089
    {NULL, NULL}
};

static const vshCmdOptDef opts_secret_set_value[] = {
13090 13091
    {"secret", VSH_OT_DATA, VSH_OFLAG_REQ, N_("secret UUID")},
    {"base64", VSH_OT_DATA, VSH_OFLAG_REQ, N_("base64-encoded secret value")},
13092 13093 13094
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
13095
static bool
13096 13097 13098 13099
cmdSecretSetValue(vshControl *ctl, const vshCmd *cmd)
{
    virSecretPtr secret;
    size_t value_size;
13100
    const char *base64 = NULL;
13101
    char *value;
E
Eric Blake 已提交
13102 13103
    int res;
    bool ret = false;
13104

13105
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
13106
        return false;
13107 13108 13109

    secret = vshCommandOptSecret(ctl, cmd, NULL);
    if (secret == NULL)
E
Eric Blake 已提交
13110
        return false;
13111

13112
    if (vshCommandOptString(cmd, "base64", &base64) <= 0)
13113 13114 13115
        goto cleanup;

    if (!base64_decode_alloc(base64, strlen(base64), &value, &value_size)) {
J
Jim Meyering 已提交
13116
        vshError(ctl, "%s", _("Invalid base64 data"));
13117 13118 13119
        goto cleanup;
    }
    if (value == NULL) {
13120
        vshError(ctl, "%s", _("Failed to allocate memory"));
E
Eric Blake 已提交
13121
        return false;
13122 13123 13124 13125
    }

    res = virSecretSetValue(secret, (unsigned char *)value, value_size, 0);
    memset(value, 0, value_size);
13126
    VIR_FREE(value);
13127 13128

    if (res != 0) {
13129
        vshError(ctl, "%s", _("Failed to set secret value"));
13130 13131 13132
        goto cleanup;
    }
    vshPrint(ctl, "%s", _("Secret value set\n"));
E
Eric Blake 已提交
13133
    ret = true;
13134 13135 13136 13137 13138 13139 13140 13141 13142 13143

cleanup:
    virSecretFree(secret);
    return ret;
}

/*
 * "secret-get-value" command
 */
static const vshCmdInfo info_secret_get_value[] = {
13144 13145
    {"help", N_("Output a secret value")},
    {"desc", N_("Output a secret value to stdout.")},
13146 13147 13148 13149
    {NULL, NULL}
};

static const vshCmdOptDef opts_secret_get_value[] = {
13150
    {"secret", VSH_OT_DATA, VSH_OFLAG_REQ, N_("secret UUID")},
13151 13152 13153
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
13154
static bool
13155 13156 13157 13158 13159 13160
cmdSecretGetValue(vshControl *ctl, const vshCmd *cmd)
{
    virSecretPtr secret;
    char *base64;
    unsigned char *value;
    size_t value_size;
E
Eric Blake 已提交
13161
    bool ret = false;
13162

13163
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
13164
        return false;
13165 13166 13167

    secret = vshCommandOptSecret(ctl, cmd, NULL);
    if (secret == NULL)
E
Eric Blake 已提交
13168
        return false;
13169 13170 13171 13172 13173 13174 13175

    value = virSecretGetValue(secret, &value_size, 0);
    if (value == NULL)
        goto cleanup;

    base64_encode_alloc((char *)value, value_size, &base64);
    memset(value, 0, value_size);
13176
    VIR_FREE(value);
13177 13178

    if (base64 == NULL) {
13179
        vshError(ctl, "%s", _("Failed to allocate memory"));
13180 13181
        goto cleanup;
    }
13182
    vshPrint(ctl, "%s", base64);
13183
    memset(base64, 0, strlen(base64));
13184
    VIR_FREE(base64);
E
Eric Blake 已提交
13185
    ret = true;
13186 13187 13188 13189 13190 13191 13192 13193 13194 13195

cleanup:
    virSecretFree(secret);
    return ret;
}

/*
 * "secret-undefine" command
 */
static const vshCmdInfo info_secret_undefine[] = {
13196 13197
    {"help", N_("undefine a secret")},
    {"desc", N_("Undefine a secret.")},
13198 13199 13200 13201
    {NULL, NULL}
};

static const vshCmdOptDef opts_secret_undefine[] = {
13202
    {"secret", VSH_OT_DATA, VSH_OFLAG_REQ, N_("secret UUID")},
13203 13204 13205
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
13206
static bool
13207 13208 13209
cmdSecretUndefine(vshControl *ctl, const vshCmd *cmd)
{
    virSecretPtr secret;
E
Eric Blake 已提交
13210
    bool ret = false;
13211
    const char *uuid;
13212

13213
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
13214
        return false;
13215 13216 13217

    secret = vshCommandOptSecret(ctl, cmd, &uuid);
    if (secret == NULL)
E
Eric Blake 已提交
13218
        return false;
13219 13220

    if (virSecretUndefine(secret) < 0) {
13221
        vshError(ctl, _("Failed to delete secret %s"), uuid);
13222 13223 13224
        goto cleanup;
    }
    vshPrint(ctl, _("Secret %s deleted\n"), uuid);
E
Eric Blake 已提交
13225
    ret = true;
13226 13227 13228 13229 13230 13231 13232 13233 13234 13235

cleanup:
    virSecretFree(secret);
    return ret;
}

/*
 * "secret-list" command
 */
static const vshCmdInfo info_secret_list[] = {
13236 13237
    {"help", N_("list secrets")},
    {"desc", N_("Returns a list of secrets")},
13238 13239 13240
    {NULL, NULL}
};

E
Eric Blake 已提交
13241
static bool
13242 13243 13244 13245 13246
cmdSecretList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    int maxuuids = 0, i;
    char **uuids = NULL;

13247
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
13248
        return false;
13249 13250 13251

    maxuuids = virConnectNumOfSecrets(ctl->conn);
    if (maxuuids < 0) {
13252
        vshError(ctl, "%s", _("Failed to list secrets"));
E
Eric Blake 已提交
13253
        return false;
13254 13255 13256 13257 13258
    }
    uuids = vshMalloc(ctl, sizeof(*uuids) * maxuuids);

    maxuuids = virConnectListSecrets(ctl->conn, uuids, maxuuids);
    if (maxuuids < 0) {
13259
        vshError(ctl, "%s", _("Failed to list secrets"));
13260
        VIR_FREE(uuids);
E
Eric Blake 已提交
13261
        return false;
13262 13263
    }

13264
    qsort(uuids, maxuuids, sizeof(char *), vshNameSorter);
13265

13266 13267
    vshPrintExtra(ctl, "%-36s %s\n", _("UUID"), _("Usage"));
    vshPrintExtra(ctl, "-----------------------------------------------------------\n");
13268 13269

    for (i = 0; i < maxuuids; i++) {
13270 13271 13272 13273
        virSecretPtr sec = virSecretLookupByUUIDString(ctl->conn, uuids[i]);
        const char *usageType = NULL;

        if (!sec) {
13274
            VIR_FREE(uuids[i]);
13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292
            continue;
        }

        switch (virSecretGetUsageType(sec)) {
        case VIR_SECRET_USAGE_TYPE_VOLUME:
            usageType = _("Volume");
            break;
        }

        if (usageType) {
            vshPrint(ctl, "%-36s %s %s\n",
                     uuids[i], usageType,
                     virSecretGetUsageID(sec));
        } else {
            vshPrint(ctl, "%-36s %s\n",
                     uuids[i], _("Unused"));
        }
        virSecretFree(sec);
13293
        VIR_FREE(uuids[i]);
13294
    }
13295
    VIR_FREE(uuids);
E
Eric Blake 已提交
13296
    return true;
13297
}
13298 13299 13300 13301 13302


/*
 * "version" command
 */
13303
static const vshCmdInfo info_version[] = {
13304 13305
    {"help", N_("show version")},
    {"desc", N_("Display the system version information.")},
13306 13307 13308
    {NULL, NULL}
};

13309 13310 13311 13312
static const vshCmdOptDef opts_version[] = {
    {"daemon", VSH_OT_BOOL, VSH_OFLAG_NONE, N_("report daemon version too")},
    {NULL, 0, 0, NULL}
};
13313

E
Eric Blake 已提交
13314
static bool
13315
cmdVersion(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
13316 13317 13318 13319 13320 13321
{
    unsigned long hvVersion;
    const char *hvType;
    unsigned long libVersion;
    unsigned long includeVersion;
    unsigned long apiVersion;
13322
    unsigned long daemonVersion;
13323 13324 13325 13326 13327
    int ret;
    unsigned int major;
    unsigned int minor;
    unsigned int rel;

13328
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
13329
        return false;
13330 13331 13332

    hvType = virConnectGetType(ctl->conn);
    if (hvType == NULL) {
13333
        vshError(ctl, "%s", _("failed to get hypervisor type"));
E
Eric Blake 已提交
13334
        return false;
13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346
    }

    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) {
13347
        vshError(ctl, "%s", _("failed to get the library version"));
E
Eric Blake 已提交
13348
        return false;
13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365
    }
    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) {
13366
        vshError(ctl, "%s", _("failed to get the hypervisor version"));
E
Eric Blake 已提交
13367
        return false;
13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380
    }
    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);
    }
13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395

    if (vshCommandOptBool(cmd, "daemon")) {
        ret = virConnectGetLibVersion(ctl->conn, &daemonVersion);
        if (ret < 0) {
            vshError(ctl, "%s", _("failed to get the daemon version"));
        } else {
            major = daemonVersion / 1000000;
            daemonVersion %= 1000000;
            minor = daemonVersion / 1000;
            rel = daemonVersion % 1000;
            vshPrint(ctl, _("Running against daemon: %d.%d.%d\n"),
                     major, minor, rel);
        }
    }

E
Eric Blake 已提交
13396
    return true;
13397 13398
}

13399
/* Tree listing helpers.  */
13400 13401 13402 13403 13404

/* Given an index, return either the name of that device (non-NULL) or
 * of its parent (NULL if a root).  */
typedef const char * (*vshTreeLookup)(int devid, bool parent, void *opaque);

13405 13406
static int
vshTreePrintInternal(vshControl *ctl,
13407 13408
                     vshTreeLookup lookup,
                     void *opaque,
13409 13410 13411 13412 13413
                     int num_devices,
                     int devid,
                     int lastdev,
                     bool root,
                     virBufferPtr indent)
13414 13415 13416
{
    int i;
    int nextlastdev = -1;
13417
    int ret = -1;
13418
    const char *dev = (lookup)(devid, false, opaque);
13419

13420 13421
    if (virBufferError(indent))
        goto cleanup;
13422

13423 13424
    /* Print this device, with indent if not at root */
    vshPrint(ctl, "%s%s%s\n", virBufferCurrentContent(indent),
13425
             root ? "" : "+- ", dev);
13426 13427

    /* Update indent to show '|' or ' ' for child devices */
13428 13429 13430 13431 13432
    if (!root) {
        virBufferAddChar(indent, devid == lastdev ? ' ' : '|');
        virBufferAddChar(indent, ' ');
        if (virBufferError(indent))
            goto cleanup;
13433 13434 13435 13436
    }

    /* Determine the index of the last child device */
    for (i = 0 ; i < num_devices ; i++) {
13437 13438 13439
        const char *parent = (lookup)(i, true, opaque);

        if (parent && STREQ(parent, dev))
13440 13441 13442 13443
            nextlastdev = i;
    }

    /* If there is a child device, then print another blank line */
13444 13445
    if (nextlastdev != -1)
        vshPrint(ctl, "%s  |\n", virBufferCurrentContent(indent));
13446 13447

    /* Finally print all children */
13448
    virBufferAddLit(indent, "  ");
13449
    for (i = 0 ; i < num_devices ; i++) {
13450 13451 13452 13453
        const char *parent = (lookup)(i, true, opaque);

        if (parent && STREQ(parent, dev) &&
            vshTreePrintInternal(ctl, lookup, opaque,
13454 13455 13456
                                 num_devices, i, nextlastdev,
                                 false, indent) < 0)
            goto cleanup;
13457
    }
13458
    virBufferTrim(indent, "  ", -1);
13459 13460 13461

    /* If there was no child device, and we're the last in
     * a list of devices, then print another blank line */
13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472
    if (nextlastdev == -1 && devid == lastdev)
        vshPrint(ctl, "%s\n", virBufferCurrentContent(indent));

    if (!root)
        virBufferTrim(indent, NULL, 2);
    ret = 0;
cleanup:
    return ret;
}

static int
13473
vshTreePrint(vshControl *ctl, vshTreeLookup lookup, void *opaque,
13474 13475 13476 13477 13478
             int num_devices, int devid)
{
    int ret;
    virBuffer indent = VIR_BUFFER_INITIALIZER;

13479
    ret = vshTreePrintInternal(ctl, lookup, opaque, num_devices,
13480 13481 13482 13483 13484
                               devid, devid, true, &indent);
    if (ret < 0)
        vshError(ctl, "%s", _("Failed to complete tree listing"));
    virBufferFreeAndReset(&indent);
    return ret;
13485 13486
}

13487
struct vshNodeList {
13488 13489 13490 13491 13492
    char **names;
    char **parents;
};

static const char *
13493
vshNodeListLookup(int devid, bool parent, void *opaque)
13494
{
13495
    struct vshNodeList *arrays = opaque;
13496 13497 13498 13499 13500
    if (parent)
        return arrays->parents[devid];
    return arrays->names[devid];
}

13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514 13515
/*
 * "nodedev-list" command
 */
static const vshCmdInfo info_node_list_devices[] = {
    {"help", N_("enumerate devices on this host")},
    {"desc", ""},
    {NULL, NULL}
};

static const vshCmdOptDef opts_node_list_devices[] = {
    {"tree", VSH_OT_BOOL, 0, N_("list devices in a tree")},
    {"cap", VSH_OT_STRING, VSH_OFLAG_NONE, N_("capability name")},
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
13516
static bool
13517
cmdNodeListDevices(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
13518
{
13519
    const char *cap = NULL;
13520
    char **devices;
13521
    int num_devices, i;
13522
    bool tree = vshCommandOptBool(cmd, "tree");
13523
    bool ret = true;
13524

13525
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
13526
        return false;
13527

13528
    if (vshCommandOptString(cmd, "cap", &cap) <= 0)
13529 13530 13531 13532
        cap = NULL;

    num_devices = virNodeNumOfDevices(ctl->conn, cap, 0);
    if (num_devices < 0) {
13533
        vshError(ctl, "%s", _("Failed to count node devices"));
E
Eric Blake 已提交
13534
        return false;
13535
    } else if (num_devices == 0) {
E
Eric Blake 已提交
13536
        return true;
13537 13538 13539 13540 13541 13542
    }

    devices = vshMalloc(ctl, sizeof(char *) * num_devices);
    num_devices =
        virNodeListDevices(ctl->conn, cap, devices, num_devices, 0);
    if (num_devices < 0) {
13543
        vshError(ctl, "%s", _("Failed to list node devices"));
13544
        VIR_FREE(devices);
E
Eric Blake 已提交
13545
        return false;
13546
    }
13547
    qsort(&devices[0], num_devices, sizeof(char*), vshNameSorter);
13548 13549
    if (tree) {
        char **parents = vshMalloc(ctl, sizeof(char *) * num_devices);
13550
        struct vshNodeList arrays = { devices, parents };
13551

13552 13553 13554 13555
        for (i = 0; i < num_devices; i++) {
            virNodeDevicePtr dev = virNodeDeviceLookupByName(ctl->conn, devices[i]);
            if (dev && STRNEQ(devices[i], "computer")) {
                const char *parent = virNodeDeviceGetParent(dev);
E
Eric Blake 已提交
13556
                parents[i] = parent ? vshStrdup(ctl, parent) : NULL;
13557 13558 13559 13560 13561 13562
            } else {
                parents[i] = NULL;
            }
            virNodeDeviceFree(dev);
        }
        for (i = 0 ; i < num_devices ; i++) {
13563
            if (parents[i] == NULL &&
13564
                vshTreePrint(ctl, vshNodeListLookup, &arrays, num_devices,
13565
                             i) < 0)
13566
                ret = false;
13567 13568
        }
        for (i = 0 ; i < num_devices ; i++) {
13569 13570
            VIR_FREE(devices[i]);
            VIR_FREE(parents[i]);
13571
        }
13572
        VIR_FREE(parents);
13573 13574 13575
    } else {
        for (i = 0; i < num_devices; i++) {
            vshPrint(ctl, "%s\n", devices[i]);
13576
            VIR_FREE(devices[i]);
13577
        }
13578
    }
13579
    VIR_FREE(devices);
13580
    return ret;
13581 13582 13583 13584 13585 13586
}

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


static const vshCmdOptDef opts_node_device_dumpxml[] = {
13594
    {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("device key")},
13595 13596 13597
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
13598
static bool
E
Eric Blake 已提交
13599
cmdNodeDeviceDumpXML(vshControl *ctl, const vshCmd *cmd)
13600
{
13601
    const char *name = NULL;
13602
    virNodeDevicePtr device;
L
Laine Stump 已提交
13603
    char *xml;
13604

13605
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
13606
        return false;
13607
    if (vshCommandOptString(cmd, "device", &name) <= 0)
E
Eric Blake 已提交
13608
        return false;
13609
    if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) {
13610
        vshError(ctl, "%s '%s'", _("Could not find matching device"), name);
E
Eric Blake 已提交
13611
        return false;
13612 13613
    }

L
Laine Stump 已提交
13614 13615 13616
    xml = virNodeDeviceGetXMLDesc(device, 0);
    if (!xml) {
        virNodeDeviceFree(device);
E
Eric Blake 已提交
13617
        return false;
L
Laine Stump 已提交
13618 13619 13620
    }

    vshPrint(ctl, "%s\n", xml);
13621
    VIR_FREE(xml);
13622
    virNodeDeviceFree(device);
E
Eric Blake 已提交
13623
    return true;
13624 13625
}

13626
/*
13627
 * "nodedev-detach" command
13628
 */
13629 13630 13631
static const vshCmdInfo info_node_device_detach[] = {
    {"help", N_("detach node device from its device driver")},
    {"desc", N_("Detach node device from its device driver before assigning to a domain.")},
13632 13633 13634 13635
    {NULL, NULL}
};


13636
static const vshCmdOptDef opts_node_device_detach[] = {
13637
    {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("device key")},
13638 13639 13640
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
13641
static bool
13642
cmdNodeDeviceDetach (vshControl *ctl, const vshCmd *cmd)
13643
{
13644
    const char *name = NULL;
13645
    virNodeDevicePtr device;
E
Eric Blake 已提交
13646
    bool ret = true;
13647

13648
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
13649
        return false;
13650
    if (vshCommandOptString(cmd, "device", &name) <= 0)
E
Eric Blake 已提交
13651
        return false;
13652
    if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) {
13653
        vshError(ctl, "%s '%s'", _("Could not find matching device"), name);
E
Eric Blake 已提交
13654
        return false;
13655 13656
    }

13657 13658
    /* Yes, our public API is misspelled.  At least virsh can accept
     * either spelling.  */
13659
    if (virNodeDeviceDettach(device) == 0) {
13660
        vshPrint(ctl, _("Device %s detached\n"), name);
13661
    } else {
13662
        vshError(ctl, _("Failed to detach device %s"), name);
E
Eric Blake 已提交
13663
        ret = false;
13664 13665 13666 13667 13668 13669 13670 13671 13672
    }
    virNodeDeviceFree(device);
    return ret;
}

/*
 * "nodedev-reattach" command
 */
static const vshCmdInfo info_node_device_reattach[] = {
13673 13674
    {"help", N_("reattach node device to its device driver")},
    {"desc", N_("Reattach node device to its device driver once released by the domain.")},
13675 13676 13677 13678 13679
    {NULL, NULL}
};


static const vshCmdOptDef opts_node_device_reattach[] = {
13680
    {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("device key")},
13681 13682 13683
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
13684
static bool
13685 13686
cmdNodeDeviceReAttach (vshControl *ctl, const vshCmd *cmd)
{
13687
    const char *name = NULL;
13688
    virNodeDevicePtr device;
E
Eric Blake 已提交
13689
    bool ret = true;
13690

13691
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
13692
        return false;
13693
    if (vshCommandOptString(cmd, "device", &name) <= 0)
E
Eric Blake 已提交
13694
        return false;
13695
    if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) {
13696
        vshError(ctl, "%s '%s'", _("Could not find matching device"), name);
E
Eric Blake 已提交
13697
        return false;
13698 13699 13700 13701 13702
    }

    if (virNodeDeviceReAttach(device) == 0) {
        vshPrint(ctl, _("Device %s re-attached\n"), name);
    } else {
13703
        vshError(ctl, _("Failed to re-attach device %s"), name);
E
Eric Blake 已提交
13704
        ret = false;
13705 13706 13707 13708 13709 13710 13711 13712 13713
    }
    virNodeDeviceFree(device);
    return ret;
}

/*
 * "nodedev-reset" command
 */
static const vshCmdInfo info_node_device_reset[] = {
13714 13715
    {"help", N_("reset node device")},
    {"desc", N_("Reset node device before or after assigning to a domain.")},
13716 13717 13718 13719 13720
    {NULL, NULL}
};


static const vshCmdOptDef opts_node_device_reset[] = {
13721
    {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("device key")},
13722 13723 13724
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
13725
static bool
13726 13727
cmdNodeDeviceReset (vshControl *ctl, const vshCmd *cmd)
{
13728
    const char *name = NULL;
13729
    virNodeDevicePtr device;
E
Eric Blake 已提交
13730
    bool ret = true;
13731

13732
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
13733
        return false;
13734
    if (vshCommandOptString(cmd, "device", &name) <= 0)
E
Eric Blake 已提交
13735
        return false;
13736
    if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) {
13737
        vshError(ctl, "%s '%s'", _("Could not find matching device"), name);
E
Eric Blake 已提交
13738
        return false;
13739 13740 13741 13742 13743
    }

    if (virNodeDeviceReset(device) == 0) {
        vshPrint(ctl, _("Device %s reset\n"), name);
    } else {
13744
        vshError(ctl, _("Failed to reset device %s"), name);
E
Eric Blake 已提交
13745
        ret = false;
13746 13747 13748 13749 13750
    }
    virNodeDeviceFree(device);
    return ret;
}

13751
/*
E
Eric Blake 已提交
13752
 * "hostname" command
13753
 */
13754
static const vshCmdInfo info_hostname[] = {
13755
    {"help", N_("print the hypervisor hostname")},
13756
    {"desc", ""},
13757 13758 13759
    {NULL, NULL}
};

E
Eric Blake 已提交
13760
static bool
13761
cmdHostname (vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
13762 13763 13764
{
    char *hostname;

13765
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
13766
        return false;
13767 13768 13769

    hostname = virConnectGetHostname (ctl->conn);
    if (hostname == NULL) {
13770
        vshError(ctl, "%s", _("failed to get hostname"));
E
Eric Blake 已提交
13771
        return false;
13772 13773 13774
    }

    vshPrint (ctl, "%s\n", hostname);
13775
    VIR_FREE(hostname);
13776

E
Eric Blake 已提交
13777
    return true;
13778 13779 13780 13781 13782
}

/*
 * "uri" command
 */
13783
static const vshCmdInfo info_uri[] = {
13784
    {"help", N_("print the hypervisor canonical URI")},
13785
    {"desc", ""},
13786 13787 13788
    {NULL, NULL}
};

E
Eric Blake 已提交
13789
static bool
13790
cmdURI (vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
13791 13792 13793
{
    char *uri;

13794
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
13795
        return false;
13796 13797 13798

    uri = virConnectGetURI (ctl->conn);
    if (uri == NULL) {
13799
        vshError(ctl, "%s", _("failed to get URI"));
E
Eric Blake 已提交
13800
        return false;
13801 13802 13803
    }

    vshPrint (ctl, "%s\n", uri);
13804
    VIR_FREE(uri);
13805

E
Eric Blake 已提交
13806
    return true;
13807 13808
}

E
Eric Blake 已提交
13809 13810 13811 13812 13813 13814 13815 13816 13817 13818
/*
 * "sysinfo" command
 */
static const vshCmdInfo info_sysinfo[] = {
    {"help", N_("print the hypervisor sysinfo")},
    {"desc",
     N_("output an XML string for the hypervisor sysinfo, if available")},
    {NULL, NULL}
};

E
Eric Blake 已提交
13819
static bool
E
Eric Blake 已提交
13820 13821 13822 13823 13824
cmdSysinfo (vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    char *sysinfo;

    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
13825
        return false;
E
Eric Blake 已提交
13826 13827 13828 13829

    sysinfo = virConnectGetSysinfo (ctl->conn, 0);
    if (sysinfo == NULL) {
        vshError(ctl, "%s", _("failed to get sysinfo"));
E
Eric Blake 已提交
13830
        return false;
E
Eric Blake 已提交
13831 13832 13833 13834 13835
    }

    vshPrint (ctl, "%s", sysinfo);
    VIR_FREE(sysinfo);

E
Eric Blake 已提交
13836
    return true;
E
Eric Blake 已提交
13837 13838
}

13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13894 13895 13896 13897 13898 13899 13900 13901 13902 13903 13904 13905 13906 13907 13908 13909 13910 13911 13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923 13924 13925 13926 13927 13928 13929 13930 13931 13932 13933 13934 13935 13936 13937 13938 13939 13940 13941 13942 13943 13944 13945 13946 13947 13948 13949 13950 13951 13952 13953 13954 13955 13956 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009
/*
 * "domdisplay" command
 */
static const vshCmdInfo info_domdisplay[] = {
    {"help", N_("domain display connection URI")},
    {"desc", N_("Output the IP address and port number for the graphical display.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_domdisplay[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"include-password", VSH_OT_BOOL, VSH_OFLAG_NONE, N_("includes the password into the connection URI if available")},
    {NULL, 0, 0, NULL}
};

static bool
cmdDomDisplay(vshControl *ctl, const vshCmd *cmd)
{
    xmlDocPtr xml = NULL;
    xmlXPathContextPtr ctxt = NULL;
    virDomainPtr dom;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    bool ret = false;
    char *doc;
    char *xpath;
    char *listen_addr;
    int port, tls_port = 0;
    char *passwd = NULL;
    char *output = NULL;
    const char *scheme[] = { "vnc", "spice", "rdp", NULL };
    int iter = 0;
    int tmp;

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

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
        return false;

    if (!virDomainIsActive(dom)) {
        vshError(ctl, _("Domain is not running"));
        goto cleanup;
    }

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

    xml = virXMLParseStringCtxt(doc, _("(domain_definition)"), &ctxt);
    VIR_FREE(doc);
    if (!xml)
        goto cleanup;

    /* Attempt to grab our display info */
    for (iter = 0; scheme[iter] != NULL; iter++) {
        /* Create our XPATH lookup for the current display's port */
        virAsprintf(&xpath, "string(/domain/devices/graphics[@type='%s']"
                "/@port)", scheme[iter]);
        if (!xpath) {
            virReportOOMError();
            goto cleanup;
        }

        /* Attempt to get the port number for the current graphics scheme */
        tmp = virXPathInt(xpath, ctxt, &port);
        VIR_FREE(xpath);

        /* If there is no port number for this type, then jump to the next
         * scheme
         */
        if (tmp)
            continue;

        /* Create our XPATH lookup for the current display's address */
        virAsprintf(&xpath, "string(/domain/devices/graphics[@type='%s']"
                "/@listen)", scheme[iter]);
        if (!xpath) {
            virReportOOMError();
            goto cleanup;
        }

        /* Attempt to get the listening addr if set for the current
         * graphics scheme
         */
        listen_addr = virXPathString(xpath, ctxt);
        VIR_FREE(xpath);

        /* Per scheme data mangling */
        if (STREQ(scheme[iter], "vnc")) {
            /* VNC protocol handlers take their port number as 'port' - 5900 */
            port -= 5900;
        } else if (STREQ(scheme[iter], "spice")) {
            /* Create our XPATH lookup for the SPICE TLS Port */
            virAsprintf(&xpath, "string(/domain/devices/graphics[@type='%s']"
                    "/@tlsPort)", scheme[iter]);
            if (!xpath) {
                virReportOOMError();
                goto cleanup;
            }

            /* Attempt to get the TLS port number for SPICE */
            tmp = virXPathInt(xpath, ctxt, &tls_port);
            VIR_FREE(xpath);
            if (tmp)
                tls_port = 0;

            if (vshCommandOptBool(cmd, "daemon")) {
                /* Create our XPATH lookup for the SPICE password */
                virAsprintf(&xpath, "string(/domain/devices/graphics"
                        "[@type='%s']/@passwd)", scheme[iter]);
                if (!xpath) {
                    virReportOOMError();
                    goto cleanup;
                }

                /* Attempt to get the SPICE password */
                passwd = virXPathString(xpath, ctxt);
                VIR_FREE(xpath);
            }
        }

        /* Build up the full URI, starting with the scheme */
        virBufferAsprintf(&buf, "%s://", scheme[iter]);

        /* Then host name or IP */
        if (!listen_addr || STREQ((const char *)listen_addr, "0.0.0.0"))
            virBufferAddLit(&buf, "localhost");
        else
            virBufferAsprintf(&buf, "%s", listen_addr);

        VIR_FREE(listen_addr);

        /* Add the port */
        if (STREQ(scheme[iter], "spice"))
            virBufferAsprintf(&buf, "?port=%d", port);
        else
            virBufferAsprintf(&buf, ":%d", port);

        /* TLS Port */
        if (tls_port)
            virBufferAsprintf(&buf, "&tls-port=%d", tls_port);

        /* Password */
        if (passwd) {
            virBufferAsprintf(&buf, "&password=%s", passwd);
            VIR_FREE(passwd);
        }

        /* Ensure we can print our URI */
        if (virBufferError(&buf)) {
            vshPrint(ctl, "%s", _("Failed to create display URI"));
            goto cleanup;
        }

        /* Print out our full URI */
        output = virBufferContentAndReset(&buf);
        vshPrint(ctl, "%s", output);
        VIR_FREE(output);

        /* We got what we came for so return successfully */
        ret = true;
        break;
    }

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

14010 14011 14012
/*
 * "vncdisplay" command
 */
14013
static const vshCmdInfo info_vncdisplay[] = {
14014 14015
    {"help", N_("vnc display")},
    {"desc", N_("Output the IP address and port number for the VNC display.")},
14016 14017 14018
    {NULL, NULL}
};

14019
static const vshCmdOptDef opts_vncdisplay[] = {
14020
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
14021 14022 14023
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
14024
static bool
14025
cmdVNCDisplay(vshControl *ctl, const vshCmd *cmd)
14026 14027 14028 14029
{
    xmlDocPtr xml = NULL;
    xmlXPathContextPtr ctxt = NULL;
    virDomainPtr dom;
E
Eric Blake 已提交
14030
    bool ret = false;
14031
    int port = 0;
14032 14033
    char *doc = NULL;
    char *listen_addr = NULL;
14034

14035
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
14036
        return false;
14037

J
Jim Meyering 已提交
14038
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
14039
        return false;
14040

14041 14042 14043
    /* Check if the domain is active and don't rely on -1 for this */
    if (!virDomainIsActive(dom)) {
        vshError(ctl, _("Domain is not running"));
14044
        goto cleanup;
14045
    }
14046

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

14050
    if (!(xml = virXMLParseStringCtxt(doc, _("(domain_definition)"), &ctxt)))
14051
        goto cleanup;
14052 14053 14054 14055 14056

    /* Get the VNC port */
    if (virXPathInt("string(/domain/devices/graphics[@type='vnc']/@port)",
                    ctxt, &port)) {
        vshError(ctl, _("Failed to get VNC port. Is this domain using VNC?"));
14057
        goto cleanup;
14058
    }
14059

14060 14061 14062
    listen_addr = virXPathString("string(/domain/devices/graphics"
                                 "[@type='vnc']/@listen)", ctxt);
    if (listen_addr == NULL || STREQ(listen_addr, "0.0.0.0"))
14063
        vshPrint(ctl, ":%d\n", port-5900);
14064 14065 14066
    else
        vshPrint(ctl, "%s:%d\n", listen_addr, port-5900);

E
Eric Blake 已提交
14067
    ret = true;
14068 14069

 cleanup:
14070 14071
    VIR_FREE(doc);
    VIR_FREE(listen_addr);
14072
    xmlXPathFreeContext(ctxt);
14073
    xmlFreeDoc(xml);
14074 14075 14076 14077 14078 14079 14080
    virDomainFree(dom);
    return ret;
}

/*
 * "ttyconsole" command
 */
14081
static const vshCmdInfo info_ttyconsole[] = {
14082 14083
    {"help", N_("tty console")},
    {"desc", N_("Output the device for the TTY console.")},
14084 14085 14086
    {NULL, NULL}
};

14087
static const vshCmdOptDef opts_ttyconsole[] = {
14088
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
14089 14090 14091
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
14092
static bool
14093
cmdTTYConsole(vshControl *ctl, const vshCmd *cmd)
14094 14095 14096 14097 14098
{
    xmlDocPtr xml = NULL;
    xmlXPathObjectPtr obj = NULL;
    xmlXPathContextPtr ctxt = NULL;
    virDomainPtr dom;
E
Eric Blake 已提交
14099
    bool ret = false;
14100 14101
    char *doc;

14102
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
14103
        return false;
14104

J
Jim Meyering 已提交
14105
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
14106
        return false;
14107 14108 14109 14110 14111

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

14112
    xml = virXMLParseStringCtxt(doc, _("(domain_definition)"), &ctxt);
14113
    VIR_FREE(doc);
14114 14115 14116 14117
    if (!xml)
        goto cleanup;

    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/console/@tty)", ctxt);
E
Eric Blake 已提交
14118 14119
    if (obj == NULL || obj->type != XPATH_STRING ||
        obj->stringval == NULL || obj->stringval[0] == 0) {
14120 14121 14122
        goto cleanup;
    }
    vshPrint(ctl, "%s\n", (const char *)obj->stringval);
E
Eric Blake 已提交
14123
    ret = true;
14124 14125 14126 14127

 cleanup:
    xmlXPathFreeObject(obj);
    xmlXPathFreeContext(ctxt);
14128
    xmlFreeDoc(xml);
14129 14130 14131 14132 14133 14134
    virDomainFree(dom);
    return ret;
}

/*
 * "attach-device" command
14135
 */
14136
static const vshCmdInfo info_attach_device[] = {
14137 14138
    {"help", N_("attach device from an XML file")},
    {"desc", N_("Attach device from an XML <file>.")},
14139 14140 14141
    {NULL, NULL}
};

14142
static const vshCmdOptDef opts_attach_device[] = {
14143 14144
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"file",   VSH_OT_DATA, VSH_OFLAG_REQ, N_("XML file")},
14145 14146
    {"persistent", VSH_OT_ALIAS, 0, "config"},
    {"config", VSH_OT_BOOL, 0, N_("affect next boot")},
14147 14148 14149
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
14150
static bool
14151
cmdAttachDevice(vshControl *ctl, const vshCmd *cmd)
14152 14153
{
    virDomainPtr dom;
14154
    const char *from = NULL;
14155
    char *buffer;
W
Wen Congyang 已提交
14156
    int ret;
J
Jim Fehlig 已提交
14157
    unsigned int flags;
14158

14159
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
14160
        return false;
14161

J
Jim Meyering 已提交
14162
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
14163
        return false;
14164

14165
    if (vshCommandOptString(cmd, "file", &from) <= 0) {
14166
        virDomainFree(dom);
E
Eric Blake 已提交
14167
        return false;
14168 14169
    }

14170
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) {
14171
        virshReportError(ctl);
14172
        virDomainFree(dom);
E
Eric Blake 已提交
14173
        return false;
14174
    }
14175

14176
    if (vshCommandOptBool(cmd, "config")) {
14177
        flags = VIR_DOMAIN_AFFECT_CONFIG;
J
Jim Fehlig 已提交
14178
        if (virDomainIsActive(dom) == 1)
14179
           flags |= VIR_DOMAIN_AFFECT_LIVE;
J
Jim Fehlig 已提交
14180 14181 14182 14183
        ret = virDomainAttachDeviceFlags(dom, buffer, flags);
    } else {
        ret = virDomainAttachDevice(dom, buffer);
    }
14184
    VIR_FREE(buffer);
14185 14186

    if (ret < 0) {
14187
        vshError(ctl, _("Failed to attach device from %s"), from);
14188
        virDomainFree(dom);
E
Eric Blake 已提交
14189
        return false;
14190
    } else {
J
Jim Meyering 已提交
14191
        vshPrint(ctl, "%s", _("Device attached successfully\n"));
14192 14193 14194
    }

    virDomainFree(dom);
E
Eric Blake 已提交
14195
    return true;
14196 14197
}

14198 14199 14200 14201 14202 14203 14204
/**
 * Check if n1 is superset of n2, meaning n1 contains all elements and
 * attributes as n2 at least. Including children.
 * @n1 first node
 * @n2 second node
 * returns true in case n1 covers n2, false otherwise.
 */
14205
ATTRIBUTE_UNUSED
14206 14207 14208 14209 14210 14211 14212 14213 14214
static bool
vshNodeIsSuperset(xmlNodePtr n1, xmlNodePtr n2)
{
    xmlNodePtr child1, child2;
    xmlAttrPtr attr;
    char *prop1, *prop2;
    bool found;
    bool visited;
    bool ret = false;
E
Eric Blake 已提交
14215
    long n1_child_size, n2_child_size, n1_iter;
14216 14217 14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243
    virBitmapPtr bitmap;

    if (!n1 && !n2)
        return true;

    if (!n1 || !n2)
        return false;

    if (!xmlStrEqual(n1->name, n2->name))
        return false;

    /* Iterate over n2 attributes and check if n1 contains them*/
    attr = n2->properties;
    while (attr) {
        if (attr->type == XML_ATTRIBUTE_NODE) {
            prop1 = virXMLPropString(n1, (const char *) attr->name);
            prop2 = virXMLPropString(n2, (const char *) attr->name);
            if (STRNEQ_NULLABLE(prop1, prop2)) {
                xmlFree(prop1);
                xmlFree(prop2);
                return false;
            }
            xmlFree(prop1);
            xmlFree(prop2);
        }
        attr = attr->next;
    }

E
Eric Blake 已提交
14244 14245 14246 14247
    n1_child_size = virXMLChildElementCount(n1);
    n2_child_size = virXMLChildElementCount(n2);
    if (n1_child_size < 0 || n2_child_size < 0 ||
        n1_child_size < n2_child_size)
14248 14249
        return false;

14250 14251 14252
    if (n1_child_size == 0 && n2_child_size == 0)
        return true;

14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316 14317 14318 14319 14320 14321 14322 14323 14324 14325 14326 14327 14328 14329 14330
    if (!(bitmap = virBitmapAlloc(n1_child_size))) {
        virReportOOMError();
        return false;
    }

    child2 = n2->children;
    while (child2) {
        if (child2->type != XML_ELEMENT_NODE) {
            child2 = child2->next;
            continue;
        }

        child1 = n1->children;
        n1_iter = 0;
        found = false;
        while (child1) {
            if (child1->type != XML_ELEMENT_NODE) {
                child1 = child1->next;
                continue;
            }

            if (virBitmapGetBit(bitmap, n1_iter, &visited) < 0) {
                vshError(NULL, "%s", _("Bad child elements counting."));
                goto cleanup;
            }

            if (visited) {
                child1 = child1->next;
                n1_iter++;
                continue;
            }

            if (xmlStrEqual(child1->name, child2->name)) {
                found = true;
                if (virBitmapSetBit(bitmap, n1_iter) < 0) {
                    vshError(NULL, "%s", _("Bad child elements counting."));
                    goto cleanup;
                }

                if (!vshNodeIsSuperset(child1, child2))
                    goto cleanup;

                break;
            }

            child1 = child1->next;
            n1_iter++;
        }

        if (!found)
            goto cleanup;

        child2 = child2->next;
    }

    ret = true;

cleanup:
    virBitmapFree(bitmap);
    return ret;
}

/**
 * vshCompleteXMLFromDomain:
 * @ctl vshControl for error messages printing
 * @dom domain
 * @oldXML device XML before
 * @newXML and after completion
 *
 * For given domain and (probably incomplete) device XML specification try to
 * find such device in domain and complete missing parts. This is however
 * possible only when given device XML is sufficiently precise so it addresses
 * only one device.
 *
 * Returns -2 when no such device exists in domain, -3 when given XML selects many
 *          (is too ambiguous), 0 in case of success. Otherwise returns -1. @newXML
 *          is touched only in case of success.
 */
14331
ATTRIBUTE_UNUSED
14332 14333 14334 14335 14336 14337 14338 14339 14340 14341 14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363 14364 14365 14366 14367 14368 14369 14370 14371 14372 14373 14374 14375 14376 14377 14378 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427 14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443
static int
vshCompleteXMLFromDomain(vshControl *ctl, virDomainPtr dom, char *oldXML,
                         char **newXML)
{
    int funcRet = -1;
    char *domXML = NULL;
    xmlDocPtr domDoc = NULL, devDoc = NULL;
    xmlNodePtr node = NULL;
    xmlXPathContextPtr domCtxt = NULL, devCtxt = NULL;
    xmlNodePtr *devices = NULL;
    xmlSaveCtxtPtr sctxt = NULL;
    int devices_size;
    char *xpath = NULL;
    xmlBufferPtr buf = NULL;
    int i = 0;
    int indx = -1;

    if (!(domXML = virDomainGetXMLDesc(dom, 0))) {
        vshError(ctl, _("couldn't get XML description of domain %s"),
                 virDomainGetName(dom));
        goto cleanup;
    }

    domDoc = virXMLParseStringCtxt(domXML, _("(domain_definition)"), &domCtxt);
    if (!domDoc) {
        vshError(ctl, _("Failed to parse domain definition xml"));
        goto cleanup;
    }

    devDoc = virXMLParseStringCtxt(oldXML, _("(device_definition)"), &devCtxt);
    if (!devDoc) {
        vshError(ctl, _("Failed to parse device definition xml"));
        goto cleanup;
    }

    node = xmlDocGetRootElement(devDoc);

    buf = xmlBufferCreate();
    if (!buf) {
        vshError(ctl, "%s", _("out of memory"));
        goto cleanup;
    }

    /* Get all possible devices */
    virAsprintf(&xpath, "/domain/devices/%s", node->name);
    if (!xpath) {
        virReportOOMError();
        goto cleanup;
    }
    devices_size = virXPathNodeSet(xpath, domCtxt, &devices);

    if (devices_size < 0) {
        /* error */
        vshError(ctl, "%s", _("error when selecting nodes"));
        goto cleanup;
    } else if (devices_size == 0) {
        /* no such device */
        funcRet = -2;
        goto cleanup;
    }

    /* and refine */
    for (i = 0; i < devices_size; i++) {
        if (vshNodeIsSuperset(devices[i], node)) {
            if (indx >= 0) {
                funcRet = -3; /* ambiguous */
                goto cleanup;
            }
            indx = i;
        }
    }

    if (indx < 0) {
        funcRet = -2; /* no such device */
        goto cleanup;
    }

    vshDebug(ctl, VSH_ERR_DEBUG, "Found device at pos %d\n", indx);

    if (newXML) {
        sctxt = xmlSaveToBuffer(buf, NULL, 0);
        if (!sctxt) {
            vshError(ctl, "%s", _("failed to create document saving context"));
            goto cleanup;
        }

        xmlSaveTree(sctxt, devices[indx]);
        xmlSaveClose(sctxt);
        *newXML = (char *) xmlBufferContent(buf);
        if (!*newXML) {
            virReportOOMError();
            goto cleanup;
        }
        buf->content = NULL;
    }

    vshDebug(ctl, VSH_ERR_DEBUG, "Old xml:\n%s\nNew xml:\n%s\n", oldXML,
             newXML ? NULLSTR(*newXML) : "(null)");

    funcRet = 0;

cleanup:
    xmlBufferFree(buf);
    VIR_FREE(devices);
    xmlXPathFreeContext(devCtxt);
    xmlXPathFreeContext(domCtxt);
    xmlFreeDoc(devDoc);
    xmlFreeDoc(domDoc);
    VIR_FREE(domXML);
    VIR_FREE(xpath);
    return funcRet;
}
14444 14445 14446 14447

/*
 * "detach-device" command
 */
14448
static const vshCmdInfo info_detach_device[] = {
14449 14450
    {"help", N_("detach device from an XML file")},
    {"desc", N_("Detach device from an XML <file>")},
14451 14452 14453
    {NULL, NULL}
};

14454
static const vshCmdOptDef opts_detach_device[] = {
14455 14456
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"file",   VSH_OT_DATA, VSH_OFLAG_REQ, N_("XML file")},
14457 14458
    {"persistent", VSH_OT_ALIAS, 0, "config"},
    {"config", VSH_OT_BOOL, 0, N_("affect next boot")},
14459 14460 14461
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
14462
static bool
14463
cmdDetachDevice(vshControl *ctl, const vshCmd *cmd)
14464
{
14465
    virDomainPtr dom = NULL;
14466
    const char *from = NULL;
14467
    char *buffer = NULL;
W
Wen Congyang 已提交
14468
    int ret;
14469
    bool funcRet = false;
J
Jim Fehlig 已提交
14470
    unsigned int flags;
14471

14472
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
14473
        return false;
14474

J
Jim Meyering 已提交
14475
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
14476
        return false;
14477

14478 14479
    if (vshCommandOptString(cmd, "file", &from) <= 0)
        goto cleanup;
14480

14481
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) {
14482
        virshReportError(ctl);
14483 14484 14485
        goto cleanup;
    }

14486
    if (vshCommandOptBool(cmd, "config")) {
14487
        flags = VIR_DOMAIN_AFFECT_CONFIG;
J
Jim Fehlig 已提交
14488
        if (virDomainIsActive(dom) == 1)
14489
           flags |= VIR_DOMAIN_AFFECT_LIVE;
14490
        ret = virDomainDetachDeviceFlags(dom, buffer, flags);
J
Jim Fehlig 已提交
14491
    } else {
14492
        ret = virDomainDetachDevice(dom, buffer);
J
Jim Fehlig 已提交
14493
    }
14494 14495

    if (ret < 0) {
14496
        vshError(ctl, _("Failed to detach device from %s"), from);
14497
        goto cleanup;
14498 14499
    }

14500 14501 14502 14503 14504
    vshPrint(ctl, "%s", _("Device detached successfully\n"));
    funcRet = true;

cleanup:
    VIR_FREE(buffer);
14505
    virDomainFree(dom);
14506
    return funcRet;
14507 14508
}

14509

14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521
/*
 * "update-device" command
 */
static const vshCmdInfo info_update_device[] = {
    {"help", N_("update device from an XML file")},
    {"desc", N_("Update device from an XML <file>.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_update_device[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"file",   VSH_OT_DATA, VSH_OFLAG_REQ, N_("XML file")},
14522 14523
    {"persistent", VSH_OT_ALIAS, 0, "config"},
    {"config", VSH_OT_BOOL, 0, N_("affect next boot")},
14524
    {"force",  VSH_OT_BOOL, 0, N_("force device update")},
14525 14526 14527
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
14528
static bool
14529 14530 14531
cmdUpdateDevice(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
14532
    const char *from = NULL;
14533
    char *buffer;
W
Wen Congyang 已提交
14534
    int ret;
14535 14536
    unsigned int flags;

14537
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
14538
        return false;
14539 14540

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
E
Eric Blake 已提交
14541
        return false;
14542

14543
    if (vshCommandOptString(cmd, "file", &from) <= 0) {
14544
        virDomainFree(dom);
E
Eric Blake 已提交
14545
        return false;
14546 14547 14548
    }

    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) {
14549
        virshReportError(ctl);
14550
        virDomainFree(dom);
E
Eric Blake 已提交
14551
        return false;
14552 14553
    }

14554
    if (vshCommandOptBool(cmd, "config")) {
14555
        flags = VIR_DOMAIN_AFFECT_CONFIG;
14556
        if (virDomainIsActive(dom) == 1)
14557
           flags |= VIR_DOMAIN_AFFECT_LIVE;
14558
    } else {
14559
        flags = VIR_DOMAIN_AFFECT_LIVE;
14560
    }
14561 14562 14563 14564

    if (vshCommandOptBool(cmd, "force"))
        flags |= VIR_DOMAIN_DEVICE_MODIFY_FORCE;

14565 14566 14567 14568 14569 14570
    ret = virDomainUpdateDeviceFlags(dom, buffer, flags);
    VIR_FREE(buffer);

    if (ret < 0) {
        vshError(ctl, _("Failed to update device from %s"), from);
        virDomainFree(dom);
E
Eric Blake 已提交
14571
        return false;
14572 14573 14574 14575 14576
    } else {
        vshPrint(ctl, "%s", _("Device updated successfully\n"));
    }

    virDomainFree(dom);
E
Eric Blake 已提交
14577
    return true;
14578 14579 14580
}


14581 14582 14583
/*
 * "attach-interface" command
 */
14584
static const vshCmdInfo info_attach_interface[] = {
14585 14586
    {"help", N_("attach network interface")},
    {"desc", N_("Attach new network interface.")},
14587 14588 14589
    {NULL, NULL}
};

14590
static const vshCmdOptDef opts_attach_interface[] = {
14591 14592 14593 14594 14595 14596
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"type",   VSH_OT_DATA, VSH_OFLAG_REQ, N_("network interface type")},
    {"source", VSH_OT_DATA, VSH_OFLAG_REQ, N_("source of network interface")},
    {"target", VSH_OT_DATA, 0, N_("target network name")},
    {"mac",    VSH_OT_DATA, 0, N_("MAC address")},
    {"script", VSH_OT_DATA, 0, N_("script used to bridge network interface")},
14597
    {"model", VSH_OT_DATA, 0, N_("model type")},
14598 14599
    {"persistent", VSH_OT_ALIAS, 0, "config"},
    {"config", VSH_OT_BOOL, 0, N_("affect next boot")},
14600 14601
    {"inbound", VSH_OT_DATA, VSH_OFLAG_NONE, N_("control domain's incoming traffics")},
    {"outbound", VSH_OT_DATA, VSH_OFLAG_NONE, N_("control domain's outgoing traffics")},
14602 14603 14604
    {NULL, 0, 0, NULL}
};

14605 14606 14607
/* parse inbound and outbound which are in the format of
 * 'average,peak,burst', in which peak and burst are optional,
 * thus 'average,,burst' and 'average,peak' are also legal. */
14608
static int parseRateStr(const char *rateStr, virNetDevBandwidthRatePtr rate)
14609 14610 14611 14612 14613 14614 14615 14616 14617 14618 14619 14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639
{
    const char *average = NULL;
    char *peak = NULL, *burst = NULL;

    average = rateStr;
    if (!average)
        return -1;
    if (virStrToLong_ull(average, &peak, 10, &rate->average) < 0)
        return -1;

    /* peak will be updated to point to the end of rateStr in case
     * of 'average' */
    if (peak && *peak != '\0') {
        burst = strchr(peak + 1, ',');
        if (!(burst && (burst - peak == 1))) {
            if (virStrToLong_ull(peak + 1, &burst, 10, &rate->peak) < 0)
                return -1;
        }

        /* burst will be updated to point to the end of rateStr in case
         * of 'average,peak' */
        if (burst && *burst != '\0') {
            if (virStrToLong_ull(burst + 1, NULL, 10, &rate->burst) < 0)
                return -1;
        }
    }


    return 0;
}

E
Eric Blake 已提交
14640
static bool
14641
cmdAttachInterface(vshControl *ctl, const vshCmd *cmd)
14642 14643
{
    virDomainPtr dom = NULL;
14644
    const char *mac = NULL, *target = NULL, *script = NULL,
14645 14646
                *type = NULL, *source = NULL, *model = NULL,
                *inboundStr = NULL, *outboundStr = NULL;
14647
    virNetDevBandwidthRate inbound, outbound;
E
Eric Blake 已提交
14648
    int typ;
W
Wen Congyang 已提交
14649 14650
    int ret;
    bool functionReturn = false;
J
Jim Fehlig 已提交
14651
    unsigned int flags;
14652 14653
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char *xml;
14654

14655
    if (!vshConnectionUsability(ctl, ctl->conn))
14656 14657
        goto cleanup;

J
Jim Meyering 已提交
14658
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
14659 14660
        goto cleanup;

14661
    if (vshCommandOptString(cmd, "type", &type) <= 0)
14662 14663
        goto cleanup;

14664 14665 14666 14667
    if (vshCommandOptString(cmd, "source", &source) < 0 ||
        vshCommandOptString(cmd, "target", &target) < 0 ||
        vshCommandOptString(cmd, "mac", &mac) < 0 ||
        vshCommandOptString(cmd, "script", &script) < 0 ||
14668 14669 14670
        vshCommandOptString(cmd, "model", &model) < 0 ||
        vshCommandOptString(cmd, "inbound", &inboundStr) < 0 ||
        vshCommandOptString(cmd, "outbound", &outboundStr) < 0) {
14671
        vshError(ctl, "missing argument");
14672
        goto cleanup;
14673
    }
14674 14675

    /* check interface type */
14676
    if (STREQ(type, "network")) {
14677
        typ = 1;
14678
    } else if (STREQ(type, "bridge")) {
14679 14680
        typ = 2;
    } else {
E
Eric Blake 已提交
14681 14682
        vshError(ctl, _("No support for %s in command 'attach-interface'"),
                 type);
14683 14684 14685
        goto cleanup;
    }

14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708
    if (inboundStr) {
        memset(&inbound, 0, sizeof(inbound));
        if (parseRateStr(inboundStr, &inbound) < 0) {
            vshError(ctl, _("inbound format is incorrect"));
            goto cleanup;
        }
        if (inbound.average == 0) {
            vshError(ctl, _("inbound average is mandatory"));
            goto cleanup;
        }
    }
    if (outboundStr) {
        memset(&outbound, 0, sizeof(outbound));
        if (parseRateStr(outboundStr, &outbound) < 0) {
            vshError(ctl, _("outbound format is incorrect"));
            goto cleanup;
        }
        if (outbound.average == 0) {
            vshError(ctl, _("outbound average is mandatory"));
            goto cleanup;
        }
    }

14709
    /* Make XML of interface */
14710
    virBufferAsprintf(&buf, "<interface type='%s'>\n", type);
14711

14712
    if (typ == 1)
14713
        virBufferAsprintf(&buf, "  <source network='%s'/>\n", source);
14714
    else if (typ == 2)
14715
        virBufferAsprintf(&buf, "  <source bridge='%s'/>\n", source);
14716

14717
    if (target != NULL)
14718
        virBufferAsprintf(&buf, "  <target dev='%s'/>\n", target);
14719
    if (mac != NULL)
14720
        virBufferAsprintf(&buf, "  <mac address='%s'/>\n", mac);
14721
    if (script != NULL)
14722
        virBufferAsprintf(&buf, "  <script path='%s'/>\n", script);
14723
    if (model != NULL)
14724
        virBufferAsprintf(&buf, "  <model type='%s'/>\n", model);
14725

14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14738 14739 14740 14741 14742 14743 14744 14745 14746
    if (inboundStr || outboundStr) {
        virBufferAsprintf(&buf, "  <bandwidth>\n");
        if (inboundStr && inbound.average > 0) {
            virBufferAsprintf(&buf, "    <inbound average='%llu'", inbound.average);
            if (inbound.peak > 0)
                virBufferAsprintf(&buf, " peak='%llu'", inbound.peak);
            if (inbound.burst > 0)
                virBufferAsprintf(&buf, " burst='%llu'", inbound.burst);
            virBufferAsprintf(&buf, "/>\n");
        }
        if (outboundStr && outbound.average > 0) {
            virBufferAsprintf(&buf, "    <outbound average='%llu'", outbound.average);
            if (outbound.peak > 0)
                virBufferAsprintf(&buf, " peak='%llu'", outbound.peak);
            if (outbound.burst > 0)
                virBufferAsprintf(&buf, " burst='%llu'", outbound.burst);
            virBufferAsprintf(&buf, "/>\n");
        }
        virBufferAsprintf(&buf, "  </bandwidth>\n");
    }

14747
    virBufferAddLit(&buf, "</interface>\n");
14748

14749 14750
    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
W
Wen Congyang 已提交
14751
        goto cleanup;
14752 14753
    }

14754
    xml = virBufferContentAndReset(&buf);
14755

14756
    if (vshCommandOptBool(cmd, "config")) {
14757
        flags = VIR_DOMAIN_AFFECT_CONFIG;
J
Jim Fehlig 已提交
14758
        if (virDomainIsActive(dom) == 1)
14759
            flags |= VIR_DOMAIN_AFFECT_LIVE;
14760
        ret = virDomainAttachDeviceFlags(dom, xml, flags);
14761
    } else {
14762
        ret = virDomainAttachDevice(dom, xml);
14763
    }
14764

14765 14766
    VIR_FREE(xml);

J
Jim Fehlig 已提交
14767
    if (ret != 0) {
L
Laine Stump 已提交
14768
        vshError(ctl, "%s", _("Failed to attach interface"));
J
Jim Fehlig 已提交
14769 14770
    } else {
        vshPrint(ctl, "%s", _("Interface attached successfully\n"));
W
Wen Congyang 已提交
14771
        functionReturn = true;
J
Jim Fehlig 已提交
14772
    }
14773 14774 14775 14776

 cleanup:
    if (dom)
        virDomainFree(dom);
14777
    virBufferFreeAndReset(&buf);
W
Wen Congyang 已提交
14778
    return functionReturn;
14779 14780 14781 14782 14783
}

/*
 * "detach-interface" command
 */
14784
static const vshCmdInfo info_detach_interface[] = {
14785 14786
    {"help", N_("detach network interface")},
    {"desc", N_("Detach network interface.")},
14787 14788 14789
    {NULL, NULL}
};

14790
static const vshCmdOptDef opts_detach_interface[] = {
14791 14792 14793
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"type",   VSH_OT_DATA, VSH_OFLAG_REQ, N_("network interface type")},
    {"mac",    VSH_OT_STRING, 0, N_("MAC address")},
14794 14795
    {"persistent", VSH_OT_ALIAS, 0, "config"},
    {"config", VSH_OT_BOOL, 0, N_("affect next boot")},
14796 14797 14798
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
14799
static bool
14800
cmdDetachInterface(vshControl *ctl, const vshCmd *cmd)
14801 14802 14803 14804 14805 14806 14807
{
    virDomainPtr dom = NULL;
    xmlDocPtr xml = NULL;
    xmlXPathObjectPtr obj=NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlNodePtr cur = NULL;
    xmlBufferPtr xml_buf = NULL;
14808
    const char *mac =NULL, *type = NULL;
14809
    char *doc;
14810
    char buf[64];
E
Eric Blake 已提交
14811
    int i = 0, diff_mac;
W
Wen Congyang 已提交
14812 14813
    int ret;
    int functionReturn = false;
J
Jim Fehlig 已提交
14814
    unsigned int flags;
14815

14816
    if (!vshConnectionUsability(ctl, ctl->conn))
14817 14818
        goto cleanup;

J
Jim Meyering 已提交
14819
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
14820 14821
        goto cleanup;

14822
    if (vshCommandOptString(cmd, "type", &type) <= 0)
14823 14824
        goto cleanup;

14825 14826
    if (vshCommandOptString(cmd, "mac", &mac) < 0) {
        vshError(ctl, "%s", _("missing option"));
14827
        goto cleanup;
14828
    }
14829 14830 14831 14832 14833

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

14834
    xml = virXMLParseStringCtxt(doc, _("(domain_definition)"), &ctxt);
14835
    VIR_FREE(doc);
14836
    if (!xml) {
14837
        vshError(ctl, "%s", _("Failed to get interface information"));
14838 14839 14840
        goto cleanup;
    }

E
Eric Blake 已提交
14841
    snprintf(buf, sizeof(buf), "/domain/devices/interface[@type='%s']", type);
14842
    obj = xmlXPathEval(BAD_CAST buf, ctxt);
E
Eric Blake 已提交
14843 14844
    if (obj == NULL || obj->type != XPATH_NODESET ||
        obj->nodesetval == NULL || obj->nodesetval->nodeNr == 0) {
14845
        vshError(ctl, _("No found interface whose type is %s"), type);
14846 14847 14848
        goto cleanup;
    }

E
Eric Blake 已提交
14849
    if (!mac && obj->nodesetval->nodeNr > 1) {
14850 14851 14852 14853 14854
        vshError(ctl, _("Domain has %d interfaces. Please specify which one "
                        "to detach using --mac"), obj->nodesetval->nodeNr);
        goto cleanup;
    }

14855 14856 14857 14858 14859 14860 14861
    if (!mac)
        goto hit;

    /* search mac */
    for (; i < obj->nodesetval->nodeNr; i++) {
        cur = obj->nodesetval->nodeTab[i]->children;
        while (cur != NULL) {
14862 14863 14864
            if (cur->type == XML_ELEMENT_NODE &&
                xmlStrEqual(cur->name, BAD_CAST "mac")) {
                char *tmp_mac = virXMLPropString(cur, "address");
14865
                diff_mac = virMacAddrCompare(tmp_mac, mac);
14866
                VIR_FREE(tmp_mac);
14867 14868 14869 14870 14871 14872 14873
                if (!diff_mac) {
                    goto hit;
                }
            }
            cur = cur->next;
        }
    }
14874
    vshError(ctl, _("No found interface whose MAC address is %s"), mac);
14875 14876 14877 14878 14879
    goto cleanup;

 hit:
    xml_buf = xmlBufferCreate();
    if (!xml_buf) {
14880
        vshError(ctl, "%s", _("Failed to allocate memory"));
14881 14882 14883
        goto cleanup;
    }

14884
    if (xmlNodeDump(xml_buf, xml, obj->nodesetval->nodeTab[i], 0, 0) < 0) {
14885
        vshError(ctl, "%s", _("Failed to create XML"));
14886 14887 14888
        goto cleanup;
    }

14889
    if (vshCommandOptBool(cmd, "config")) {
14890
        flags = VIR_DOMAIN_AFFECT_CONFIG;
J
Jim Fehlig 已提交
14891
        if (virDomainIsActive(dom) == 1)
14892
            flags |= VIR_DOMAIN_AFFECT_LIVE;
J
Jim Fehlig 已提交
14893 14894 14895 14896 14897 14898 14899 14900
        ret = virDomainDetachDeviceFlags(dom,
                                         (char *)xmlBufferContent(xml_buf),
                                         flags);
    } else {
        ret = virDomainDetachDevice(dom, (char *)xmlBufferContent(xml_buf));
    }

    if (ret != 0) {
L
Laine Stump 已提交
14901
        vshError(ctl, "%s", _("Failed to detach interface"));
J
Jim Fehlig 已提交
14902
    } else {
J
Jim Meyering 已提交
14903
        vshPrint(ctl, "%s", _("Interface detached successfully\n"));
W
Wen Congyang 已提交
14904
        functionReturn = true;
14905
    }
14906 14907 14908 14909

 cleanup:
    if (dom)
        virDomainFree(dom);
14910
    xmlXPathFreeObject(obj);
14911
    xmlXPathFreeContext(ctxt);
14912 14913
    xmlFreeDoc(xml);
    xmlBufferFree(xml_buf);
W
Wen Congyang 已提交
14914
    return functionReturn;
14915 14916 14917 14918 14919
}

/*
 * "attach-disk" command
 */
14920
static const vshCmdInfo info_attach_disk[] = {
14921 14922
    {"help", N_("attach disk device")},
    {"desc", N_("Attach new disk device.")},
14923 14924 14925
    {NULL, NULL}
};

14926
static const vshCmdOptDef opts_attach_disk[] = {
14927
    {"domain",  VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
14928 14929
    {"source",  VSH_OT_DATA, VSH_OFLAG_REQ | VSH_OFLAG_EMPTY_OK,
     N_("source of disk device")},
14930 14931 14932
    {"target",  VSH_OT_DATA, VSH_OFLAG_REQ, N_("target of disk device")},
    {"driver",    VSH_OT_STRING, 0, N_("driver of disk device")},
    {"subdriver", VSH_OT_STRING, 0, N_("subdriver of disk device")},
14933
    {"cache",     VSH_OT_STRING, 0, N_("cache mode of disk device")},
14934 14935
    {"type",    VSH_OT_STRING, 0, N_("target device type")},
    {"mode",    VSH_OT_STRING, 0, N_("mode of device reading and writing")},
14936 14937
    {"persistent", VSH_OT_ALIAS, 0, "config"},
    {"config", VSH_OT_BOOL, 0, N_("affect next boot")},
14938
    {"sourcetype", VSH_OT_STRING, 0, N_("type of source (block|file)")},
14939 14940
    {"serial", VSH_OT_STRING, 0, N_("serial of disk device")},
    {"shareable", VSH_OT_BOOL, 0, N_("shareable between domains")},
14941
    {"rawio", VSH_OT_BOOL, 0, N_("needs rawio capability")},
14942
    {"address", VSH_OT_STRING, 0, N_("address of disk device")},
14943 14944
    {"multifunction", VSH_OT_BOOL, 0,
     N_("use multifunction pci under specified address")},
14945 14946 14947
    {NULL, 0, 0, NULL}
};

14948 14949 14950 14951 14952 14953 14954 14955 14956 14957 14958 14959 14960 14961 14962 14963 14964 14965 14966 14967 14968 14969 14970 14971 14972 14973 14974 14975 14976 14977 14978 14979 14980 14981 14982 14983 14984 14985 14986 14987 14988 14989 14990 14991 14992 14993 14994 14995 14996 14997 14998 14999 15000 15001 15002 15003 15004 15005 15006 15007 15008 15009 15010 15011 15012 15013 15014 15015 15016 15017 15018 15019 15020 15021 15022 15023 15024 15025 15026 15027 15028 15029 15030 15031 15032 15033 15034 15035 15036 15037 15038 15039 15040 15041 15042 15043 15044 15045 15046 15047 15048 15049 15050 15051 15052 15053 15054 15055 15056 15057 15058 15059 15060 15061 15062 15063 15064 15065 15066 15067 15068 15069 15070 15071 15072 15073 15074 15075 15076 15077 15078 15079 15080 15081 15082 15083 15084 15085 15086 15087 15088 15089 15090 15091 15092 15093 15094
enum {
    DISK_ADDR_TYPE_INVALID,
    DISK_ADDR_TYPE_PCI,
    DISK_ADDR_TYPE_SCSI,
    DISK_ADDR_TYPE_IDE,
};

struct PCIAddress {
    unsigned int domain;
    unsigned int bus;
    unsigned int slot;
    unsigned int function;
};

struct SCSIAddress {
    unsigned int controller;
    unsigned int bus;
    unsigned int unit;
};

struct IDEAddress {
    unsigned int controller;
    unsigned int bus;
    unsigned int unit;
};

struct DiskAddress {
    int type;
    union {
        struct PCIAddress pci;
        struct SCSIAddress scsi;
        struct IDEAddress ide;
    } addr;
};

static int str2PCIAddress(const char *str, struct PCIAddress *pciAddr)
{
    char *domain, *bus, *slot, *function;

    if (!pciAddr)
        return -1;
    if (!str)
        return -1;

    domain = (char *)str;

    if (virStrToLong_ui(domain, &bus, 0, &pciAddr->domain) != 0)
        return -1;

    bus++;
    if (virStrToLong_ui(bus, &slot, 0, &pciAddr->bus) != 0)
        return -1;

    slot++;
    if (virStrToLong_ui(slot, &function, 0, &pciAddr->slot) != 0)
        return -1;

    function++;
    if (virStrToLong_ui(function, NULL, 0, &pciAddr->function) != 0)
        return -1;

    return 0;
}

static int str2SCSIAddress(const char *str, struct SCSIAddress *scsiAddr)
{
    char *controller, *bus, *unit;

    if (!scsiAddr)
        return -1;
    if (!str)
        return -1;

    controller = (char *)str;

    if (virStrToLong_ui(controller, &bus, 0, &scsiAddr->controller) != 0)
        return -1;

    bus++;
    if (virStrToLong_ui(bus, &unit, 0, &scsiAddr->bus) != 0)
        return -1;

    unit++;
    if (virStrToLong_ui(unit, NULL, 0, &scsiAddr->unit) != 0)
        return -1;

    return 0;
}

static int str2IDEAddress(const char *str, struct IDEAddress *ideAddr)
{
    char *controller, *bus, *unit;

    if (!ideAddr)
        return -1;
    if (!str)
        return -1;

    controller = (char *)str;

    if (virStrToLong_ui(controller, &bus, 0, &ideAddr->controller) != 0)
        return -1;

    bus++;
    if (virStrToLong_ui(bus, &unit, 0, &ideAddr->bus) != 0)
        return -1;

    unit++;
    if (virStrToLong_ui(unit, NULL, 0, &ideAddr->unit) != 0)
        return -1;

    return 0;
}

/* pci address pci:0000.00.0x0a.0 (domain:bus:slot:function)
 * ide disk address: ide:00.00.0 (controller:bus:unit)
 * scsi disk address: scsi:00.00.0 (controller:bus:unit)
 */

static int str2DiskAddress(const char *str, struct DiskAddress *diskAddr)
{
    char *type, *addr;

    if (!diskAddr)
        return -1;
    if (!str)
        return -1;

    type = (char *)str;
    addr = strchr(type, ':');
    if (!addr)
        return -1;

    if (STREQLEN(type, "pci", addr - type)) {
        diskAddr->type = DISK_ADDR_TYPE_PCI;
        return str2PCIAddress(addr + 1, &diskAddr->addr.pci);
    } else if (STREQLEN(type, "scsi", addr - type)) {
        diskAddr->type = DISK_ADDR_TYPE_SCSI;
        return str2SCSIAddress(addr + 1, &diskAddr->addr.scsi);
    } else if (STREQLEN(type, "ide", addr - type)) {
        diskAddr->type = DISK_ADDR_TYPE_IDE;
        return str2IDEAddress(addr + 1, &diskAddr->addr.ide);
    }

    return -1;
}

E
Eric Blake 已提交
15095
static bool
15096
cmdAttachDisk(vshControl *ctl, const vshCmd *cmd)
15097 15098
{
    virDomainPtr dom = NULL;
15099
    const char *source = NULL, *target = NULL, *driver = NULL,
15100 15101 15102
                *subdriver = NULL, *type = NULL, *mode = NULL,
                *cache = NULL, *serial = NULL, *straddr = NULL;
    struct DiskAddress diskAddr;
W
Wen Congyang 已提交
15103 15104
    bool isFile = false, functionReturn = false;
    int ret;
J
Jim Fehlig 已提交
15105
    unsigned int flags;
15106
    const char *stype = NULL;
15107 15108
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char *xml;
O
Osier Yang 已提交
15109
    struct stat st;
15110

15111
    if (!vshConnectionUsability(ctl, ctl->conn))
15112 15113
        goto cleanup;

J
Jim Meyering 已提交
15114
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
15115 15116
        goto cleanup;

15117
    if (vshCommandOptString(cmd, "source", &source) <= 0)
15118
        goto cleanup;
15119 15120 15121 15122
    /* Allow empty string as a placeholder that implies no source, for
     * use in adding a cdrom drive with no disk.  */
    if (!*source)
        source = NULL;
15123

15124
    if (vshCommandOptString(cmd, "target", &target) <= 0)
15125 15126
        goto cleanup;

15127 15128 15129 15130
    if (vshCommandOptString(cmd, "driver", &driver) < 0 ||
        vshCommandOptString(cmd, "subdriver", &subdriver) < 0 ||
        vshCommandOptString(cmd, "type", &type) < 0 ||
        vshCommandOptString(cmd, "mode", &mode) < 0 ||
15131 15132 15133
        vshCommandOptString(cmd, "cache", &cache) < 0 ||
        vshCommandOptString(cmd, "serial", &serial) < 0 ||
        vshCommandOptString(cmd, "address", &straddr) < 0 ||
15134
        vshCommandOptString(cmd, "sourcetype", &stype) < 0) {
15135
        vshError(ctl, "%s", _("missing option"));
15136 15137
        goto cleanup;
    }
15138

15139
    if (!stype) {
O
Osier Yang 已提交
15140
        if (driver && (STREQ(driver, "file") || STREQ(driver, "tap"))) {
E
Eric Blake 已提交
15141
            isFile = true;
O
Osier Yang 已提交
15142 15143 15144 15145
        } else {
            if (source && !stat(source, &st))
                isFile = S_ISREG(st.st_mode) ? true : false;
        }
15146
    } else if (STREQ(stype, "file")) {
E
Eric Blake 已提交
15147
        isFile = true;
15148 15149 15150
    } else if (STRNEQ(stype, "block")) {
        vshError(ctl, _("Unknown source type: '%s'"), stype);
        goto cleanup;
15151 15152 15153
    }

    if (mode) {
15154
        if (STRNEQ(mode, "readonly") && STRNEQ(mode, "shareable")) {
E
Eric Blake 已提交
15155 15156
            vshError(ctl, _("No support for %s in command 'attach-disk'"),
                     mode);
15157 15158 15159 15160 15161
            goto cleanup;
        }
    }

    /* Make XML of disk */
15162
    virBufferAsprintf(&buf, "<disk type='%s'",
15163 15164
                      (isFile) ? "file" : "block");
    if (type)
15165
        virBufferAsprintf(&buf, " device='%s'", type);
E
Eric Blake 已提交
15166
    if (vshCommandOptBool(cmd, "rawio"))
15167
        virBufferAddLit(&buf, " rawio='yes'");
15168 15169
    virBufferAddLit(&buf, ">\n");

15170
    if (driver || subdriver || cache) {
15171
        virBufferAsprintf(&buf, "  <driver");
15172

15173 15174 15175 15176 15177 15178
        if (driver)
            virBufferAsprintf(&buf, " name='%s'", driver);
        if (subdriver)
            virBufferAsprintf(&buf, " type='%s'", subdriver);
        if (cache)
            virBufferAsprintf(&buf, " cache='%s'", cache);
15179 15180

        virBufferAddLit(&buf, "/>\n");
15181
    }
15182

15183 15184 15185 15186
    if (source)
        virBufferAsprintf(&buf, "  <source %s='%s'/>\n",
                          (isFile) ? "file" : "dev",
                          source);
15187
    virBufferAsprintf(&buf, "  <target dev='%s'/>\n", target);
15188
    if (mode)
15189
        virBufferAsprintf(&buf, "  <%s/>\n", mode);
15190

15191 15192 15193 15194 15195 15196 15197 15198 15199 15200 15201 15202 15203 15204 15205 15206
    if (serial)
        virBufferAsprintf(&buf, "  <serial>%s</serial>\n", serial);

    if (vshCommandOptBool(cmd, "shareable"))
        virBufferAsprintf(&buf, "  <shareable/>\n");

    if (straddr) {
        if (str2DiskAddress(straddr, &diskAddr) != 0) {
            vshError(ctl, _("Invalid address."));
            goto cleanup;
        }

        if (STRPREFIX((const char *)target, "vd")) {
            if (diskAddr.type == DISK_ADDR_TYPE_PCI) {
                virBufferAsprintf(&buf,
                                  "  <address type='pci' domain='0x%04x'"
15207
                                  " bus ='0x%02x' slot='0x%02x' function='0x%0x'",
15208 15209
                                  diskAddr.addr.pci.domain, diskAddr.addr.pci.bus,
                                  diskAddr.addr.pci.slot, diskAddr.addr.pci.function);
15210 15211 15212
                if (vshCommandOptBool(cmd, "multifunction"))
                    virBufferAddLit(&buf, " multifunction='on'");
                virBufferAddLit(&buf, "/>\n");
15213 15214 15215 15216 15217 15218 15219 15220 15221 15222 15223 15224 15225 15226 15227 15228 15229 15230 15231 15232 15233 15234 15235 15236 15237 15238 15239 15240 15241
            } else {
                vshError(ctl, "%s", _("expecting a pci:0000.00.00.00 address."));
                goto cleanup;
            }
        } else if (STRPREFIX((const char *)target, "sd")) {
            if (diskAddr.type == DISK_ADDR_TYPE_SCSI) {
                virBufferAsprintf(&buf,
                                  "  <address type='drive' controller='%d'"
                                  " bus='%d' unit='%d' />\n",
                                  diskAddr.addr.scsi.controller, diskAddr.addr.scsi.bus,
                                  diskAddr.addr.scsi.unit);
            } else {
                vshError(ctl, "%s", _("expecting a scsi:00.00.00 address."));
                goto cleanup;
            }
        } else if (STRPREFIX((const char *)target, "hd")) {
            if (diskAddr.type == DISK_ADDR_TYPE_IDE) {
                virBufferAsprintf(&buf,
                                  "  <address type='drive' controller='%d'"
                                  " bus='%d' unit='%d' />\n",
                                  diskAddr.addr.ide.controller, diskAddr.addr.ide.bus,
                                  diskAddr.addr.ide.unit);
            } else {
                vshError(ctl, "%s", _("expecting an ide:00.00.00 address."));
                goto cleanup;
            }
        }
    }

15242
    virBufferAddLit(&buf, "</disk>\n");
15243

15244 15245
    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
E
Eric Blake 已提交
15246
        return false;
15247 15248
    }

15249
    xml = virBufferContentAndReset(&buf);
15250

15251
    if (vshCommandOptBool(cmd, "config")) {
15252
        flags = VIR_DOMAIN_AFFECT_CONFIG;
J
Jim Fehlig 已提交
15253
        if (virDomainIsActive(dom) == 1)
15254
            flags |= VIR_DOMAIN_AFFECT_LIVE;
15255
        ret = virDomainAttachDeviceFlags(dom, xml, flags);
J
Jim Fehlig 已提交
15256
    } else {
15257
        ret = virDomainAttachDevice(dom, xml);
J
Jim Fehlig 已提交
15258
    }
15259

15260 15261
    VIR_FREE(xml);

J
Jim Fehlig 已提交
15262
    if (ret != 0) {
L
Laine Stump 已提交
15263
        vshError(ctl, "%s", _("Failed to attach disk"));
J
Jim Fehlig 已提交
15264 15265
    } else {
        vshPrint(ctl, "%s", _("Disk attached successfully\n"));
W
Wen Congyang 已提交
15266
        functionReturn = true;
J
Jim Fehlig 已提交
15267
    }
15268 15269 15270 15271

 cleanup:
    if (dom)
        virDomainFree(dom);
15272
    virBufferFreeAndReset(&buf);
W
Wen Congyang 已提交
15273
    return functionReturn;
15274 15275
}

15276 15277 15278 15279 15280 15281 15282 15283 15284 15285 15286 15287 15288 15289 15290 15291 15292 15293 15294 15295 15296 15297 15298 15299 15300 15301 15302 15303 15304
typedef enum {
    VSH_FIND_DISK_NORMAL,
    VSH_FIND_DISK_CHANGEABLE,
} vshFindDiskType;

/* Helper function to find disk device in XML doc.  Returns the disk
 * node on success, or NULL on failure. Caller must free the result
 * @path: Fully-qualified path or target of disk device.
 * @type: Either VSH_FIND_DISK_NORMAL or VSH_FIND_DISK_CHANGEABLE.
 */
static xmlNodePtr
vshFindDisk(const char *doc,
            const char *path,
            int type)
{
    xmlDocPtr xml = NULL;
    xmlXPathObjectPtr obj= NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlNodePtr cur = NULL;
    xmlNodePtr ret = NULL;
    int i = 0;

    xml = virXMLParseStringCtxt(doc, _("(domain_definition)"), &ctxt);
    if (!xml) {
        vshError(NULL, "%s", _("Failed to get disk information"));
        goto cleanup;
    }

    obj = xmlXPathEval(BAD_CAST "/domain/devices/disk", ctxt);
E
Eric Blake 已提交
15305 15306 15307 15308
    if (obj == NULL ||
        obj->type != XPATH_NODESET ||
        obj->nodesetval == NULL ||
        obj->nodesetval->nodeNr == 0) {
15309 15310 15311 15312 15313 15314 15315 15316 15317 15318 15319 15320 15321 15322 15323 15324 15325 15326 15327 15328 15329 15330 15331 15332 15333 15334 15335 15336 15337 15338 15339 15340 15341 15342 15343 15344 15345 15346 15347 15348 15349 15350 15351 15352 15353 15354 15355 15356 15357 15358 15359 15360 15361 15362 15363 15364 15365 15366 15367 15368 15369 15370 15371 15372 15373 15374 15375 15376 15377 15378 15379 15380 15381 15382 15383 15384 15385 15386 15387 15388 15389 15390 15391 15392 15393 15394 15395 15396 15397 15398 15399 15400 15401 15402 15403 15404 15405 15406 15407 15408 15409 15410 15411 15412 15413 15414 15415 15416 15417 15418 15419 15420 15421 15422 15423 15424 15425 15426 15427 15428 15429 15430 15431 15432 15433 15434 15435 15436 15437 15438 15439 15440 15441 15442 15443 15444 15445 15446 15447 15448 15449 15450 15451 15452 15453 15454 15455 15456 15457 15458 15459 15460 15461 15462 15463 15464 15465 15466 15467 15468 15469 15470 15471 15472 15473
        vshError(NULL, "%s", _("Failed to get disk information"));
        goto cleanup;
    }

    /* search disk using @path */
    for (; i < obj->nodesetval->nodeNr; i++) {
        bool is_supported = true;

        if (type == VSH_FIND_DISK_CHANGEABLE) {
            xmlNodePtr n = obj->nodesetval->nodeTab[i];
            is_supported = false;

            /* Check if the disk is CDROM or floppy disk */
            if (xmlStrEqual(n->name, BAD_CAST "disk")) {
                char *device_value = virXMLPropString(n, "device");

                if (STREQ(device_value, "cdrom") ||
                    STREQ(device_value, "floppy"))
                    is_supported = true;

                VIR_FREE(device_value);
            }

            if (!is_supported)
                continue;
        }

        cur = obj->nodesetval->nodeTab[i]->children;
        while (cur != NULL) {
            if (cur->type == XML_ELEMENT_NODE) {
                char *tmp = NULL;

                if (xmlStrEqual(cur->name, BAD_CAST "source")) {
                    if ((tmp = virXMLPropString(cur, "file")) ||
                        (tmp = virXMLPropString(cur, "dev")) ||
                        (tmp = virXMLPropString(cur, "dir")) ||
                        (tmp = virXMLPropString(cur, "name"))) {
                    }
                } else if (xmlStrEqual(cur->name, BAD_CAST "target")) {
                    tmp = virXMLPropString(cur, "dev");
                }

                if (STREQ_NULLABLE(tmp, path)) {
                    ret = xmlCopyNode(obj->nodesetval->nodeTab[i], 1);
                    VIR_FREE(tmp);
                    goto cleanup;
                }
                VIR_FREE(tmp);
            }
            cur = cur->next;
        }
    }

    vshError(NULL, _("No found disk whose source path or target is %s"), path);

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

typedef enum {
    VSH_PREPARE_DISK_XML_NONE = 0,
    VSH_PREPARE_DISK_XML_EJECT,
    VSH_PREPARE_DISK_XML_INSERT,
    VSH_PREPARE_DISK_XML_UPDATE,
} vshPrepareDiskXMLType;

/* Helper function to prepare disk XML. Could be used for disk
 * detaching, media changing(ejecting, inserting, updating)
 * for changeable disk. Returns the processed XML as string on
 * success, or NULL on failure. Caller must free the result.
 */
static char *
vshPrepareDiskXML(xmlNodePtr disk_node,
                  const char *source,
                  const char *path,
                  int type)
{
    xmlNodePtr cur = NULL;
    xmlBufferPtr xml_buf = NULL;
    const char *disk_type = NULL;
    const char *device_type = NULL;
    xmlNodePtr new_node = NULL;
    char *ret = NULL;

    if (!disk_node)
        return NULL;

    xml_buf = xmlBufferCreate();
    if (!xml_buf) {
        vshError(NULL, "%s", _("Failed to allocate memory"));
        return NULL;
    }

    device_type = virXMLPropString(disk_node, "device");

    if (STREQ_NULLABLE(device_type, "cdrom") ||
        STREQ_NULLABLE(device_type, "floppy")) {
        bool has_source = false;
        disk_type = virXMLPropString(disk_node, "type");

        cur = disk_node->children;
        while (cur != NULL) {
            if (cur->type == XML_ELEMENT_NODE &&
                xmlStrEqual(cur->name, BAD_CAST "source")) {
                has_source = true;
                break;
            }
            cur = cur->next;
        }

        if (!has_source) {
            if (type == VSH_PREPARE_DISK_XML_EJECT) {
                vshError(NULL, _("The disk device '%s' doesn't have media"),
                         path);
                goto error;
            }

            if (source) {
                new_node = xmlNewNode(NULL, BAD_CAST "source");
                xmlNewProp(new_node, (const xmlChar *)disk_type,
                           (const xmlChar *)source);
                xmlAddChild(disk_node, new_node);
            } else if (type == VSH_PREPARE_DISK_XML_INSERT) {
                vshError(NULL, _("No source is specified for inserting media"));
                goto error;
            } else if (type == VSH_PREPARE_DISK_XML_UPDATE) {
                vshError(NULL, _("No source is specified for updating media"));
                goto error;
            }
        }

        if (has_source) {
            if (type == VSH_PREPARE_DISK_XML_INSERT) {
                vshError(NULL, _("The disk device '%s' already has media"),
                         path);
                goto error;
            }

            /* Remove the source if it tends to eject/update media. */
            xmlUnlinkNode(cur);
            xmlFreeNode(cur);

            if (source && (type == VSH_PREPARE_DISK_XML_UPDATE)) {
                new_node = xmlNewNode(NULL, BAD_CAST "source");
                xmlNewProp(new_node, (const xmlChar *)disk_type,
                           (const xmlChar *)source);
                xmlAddChild(disk_node, new_node);
            }
        }
    }

    if (xmlNodeDump(xml_buf, NULL, disk_node, 0, 0) < 0) {
        vshError(NULL, "%s", _("Failed to create XML"));
        goto error;
    }

    goto cleanup;

cleanup:
    VIR_FREE(device_type);
    VIR_FREE(disk_type);
    if (xml_buf) {
15474 15475
        int len = xmlBufferLength(xml_buf);
        if (VIR_ALLOC_N(ret, len + 1) < 0) {
15476 15477 15478
            virReportOOMError();
            return NULL;
        }
15479 15480
        memcpy(ret, (char *)xmlBufferContent(xml_buf), len);
        ret[len] = '\0';
15481 15482 15483 15484 15485 15486 15487 15488 15489 15490
        xmlBufferFree(xml_buf);
    }
    return ret;

error:
    xmlBufferFree(xml_buf);
    xml_buf = NULL;
    goto cleanup;
}

15491 15492 15493
/*
 * "detach-disk" command
 */
15494
static const vshCmdInfo info_detach_disk[] = {
15495 15496
    {"help", N_("detach disk device")},
    {"desc", N_("Detach disk device.")},
15497 15498 15499
    {NULL, NULL}
};

15500
static const vshCmdOptDef opts_detach_disk[] = {
15501 15502
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"target", VSH_OT_DATA, VSH_OFLAG_REQ, N_("target of disk device")},
15503 15504
    {"persistent", VSH_OT_ALIAS, 0, "config"},
    {"config", VSH_OT_BOOL, 0, N_("affect next boot")},
15505 15506 15507
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
15508
static bool
15509
cmdDetachDisk(vshControl *ctl, const vshCmd *cmd)
15510
{
15511
    char *disk_xml = NULL;
15512
    virDomainPtr dom = NULL;
15513
    const char *target = NULL;
A
Alex Jia 已提交
15514
    char *doc = NULL;
W
Wen Congyang 已提交
15515 15516
    int ret;
    bool functionReturn = false;
J
Jim Fehlig 已提交
15517
    unsigned int flags;
15518
    xmlNodePtr disk_node = NULL;
15519

15520
    if (!vshConnectionUsability(ctl, ctl->conn))
15521 15522
        goto cleanup;

J
Jim Meyering 已提交
15523
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
15524 15525
        goto cleanup;

15526
    if (vshCommandOptString(cmd, "target", &target) <= 0)
15527 15528 15529 15530 15531 15532
        goto cleanup;

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

15533
    if (!(disk_node = vshFindDisk(doc, target, VSH_FIND_DISK_NORMAL)))
15534 15535
        goto cleanup;

15536 15537
    if (!(disk_xml = vshPrepareDiskXML(disk_node, NULL, NULL,
                                       VSH_PREPARE_DISK_XML_NONE)))
15538 15539
        goto cleanup;

15540
    if (vshCommandOptBool(cmd, "config")) {
15541
        flags = VIR_DOMAIN_AFFECT_CONFIG;
J
Jim Fehlig 已提交
15542
        if (virDomainIsActive(dom) == 1)
15543
            flags |= VIR_DOMAIN_AFFECT_LIVE;
J
Jim Fehlig 已提交
15544
        ret = virDomainDetachDeviceFlags(dom,
15545
                                         disk_xml,
J
Jim Fehlig 已提交
15546 15547
                                         flags);
    } else {
15548
        ret = virDomainDetachDevice(dom, disk_xml);
J
Jim Fehlig 已提交
15549 15550 15551
    }

    if (ret != 0) {
L
Laine Stump 已提交
15552
        vshError(ctl, "%s", _("Failed to detach disk"));
J
Jim Fehlig 已提交
15553
    } else {
J
Jim Meyering 已提交
15554
        vshPrint(ctl, "%s", _("Disk detached successfully\n"));
W
Wen Congyang 已提交
15555
        functionReturn = true;
15556
    }
15557 15558

 cleanup:
15559 15560 15561
    xmlFreeNode(disk_node);
    VIR_FREE(disk_xml);
    VIR_FREE(doc);
15562 15563
    if (dom)
        virDomainFree(dom);
W
Wen Congyang 已提交
15564
    return functionReturn;
15565 15566
}

O
Osier Yang 已提交
15567 15568 15569 15570 15571 15572 15573 15574 15575 15576 15577 15578 15579 15580 15581 15582 15583 15584 15585 15586 15587 15588 15589 15590 15591 15592 15593 15594 15595 15596 15597 15598 15599 15600 15601 15602 15603 15604 15605 15606 15607 15608 15609 15610 15611 15612 15613 15614 15615 15616 15617 15618 15619 15620 15621 15622 15623 15624 15625 15626 15627 15628 15629 15630 15631 15632 15633 15634 15635 15636 15637 15638 15639 15640 15641 15642 15643 15644 15645 15646 15647 15648 15649 15650 15651 15652 15653 15654 15655 15656 15657 15658 15659 15660 15661 15662 15663 15664 15665 15666 15667 15668 15669 15670 15671 15672 15673 15674 15675 15676 15677 15678 15679 15680 15681 15682 15683 15684 15685 15686 15687 15688 15689 15690 15691 15692 15693 15694 15695 15696 15697 15698 15699
/*
 * "change-media" command
 */
static const vshCmdInfo info_change_media[] = {
    {"help", N_("Change media of CD or floppy drive")},
    {"desc", N_("Change media of CD or floppy drive.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_change_media[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"path", VSH_OT_DATA, VSH_OFLAG_REQ, N_("Fully-qualified path or "
                                            "target of disk device")},
    {"source", VSH_OT_DATA, 0, N_("source of the media")},
    {"eject", VSH_OT_BOOL, 0, N_("Eject the media")},
    {"insert", VSH_OT_BOOL, 0, N_("Insert the media")},
    {"update", VSH_OT_BOOL, 0, N_("Update the media")},
    {"current", VSH_OT_BOOL, 0, N_("can be either or both of --live and --config, "
                                   "depends on implementation of hypervisor driver")},
    {"live", VSH_OT_BOOL, 0, N_("alter live configuration of running domain")},
    {"config", VSH_OT_BOOL, 0, N_("alter persistent configuration, effect observed on next boot")},
    {"force",  VSH_OT_BOOL, 0, N_("force media insertion")},
    {NULL, 0, 0, NULL}
};

static bool
cmdChangeMedia(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
    const char *source = NULL;
    const char *path = NULL;
    const char *doc = NULL;
    xmlNodePtr disk_node = NULL;
    const char *disk_xml = NULL;
    int flags = 0;
    bool config, live, current, force = false;
    bool eject, insert, update = false;
    bool ret = false;
    int prepare_type = 0;
    const char *action = NULL;

    config = vshCommandOptBool(cmd, "config");
    live = vshCommandOptBool(cmd, "live");
    current = vshCommandOptBool(cmd, "current");
    force = vshCommandOptBool(cmd, "force");
    eject = vshCommandOptBool(cmd, "eject");
    insert = vshCommandOptBool(cmd, "insert");
    update = vshCommandOptBool(cmd, "update");

    if (eject + insert + update > 1) {
        vshError(ctl, "%s", _("--eject, --insert, and --update must be specified "
                            "exclusively."));
        return false;
    }

    if (eject) {
        prepare_type = VSH_PREPARE_DISK_XML_EJECT;
        action = "eject";
    }

    if (insert) {
        prepare_type = VSH_PREPARE_DISK_XML_INSERT;
        action = "insert";
    }

    if (update || (!eject && !insert)) {
        prepare_type = VSH_PREPARE_DISK_XML_UPDATE;
        action = "update";
    }

    if (current) {
        if (live || config) {
            vshError(ctl, "%s", _("--current must be specified exclusively"));
            return false;
        }
        flags = VIR_DOMAIN_AFFECT_CURRENT;
    } else {
        if (config)
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
        if (live)
            flags |= VIR_DOMAIN_AFFECT_LIVE;
    }

    if (force)
        flags |= VIR_DOMAIN_DEVICE_MODIFY_FORCE;

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

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

    if (vshCommandOptString(cmd, "path", &path) <= 0)
        goto cleanup;

    if (vshCommandOptString(cmd, "source", &source) < 0)
        goto cleanup;

    if (insert && !source) {
        vshError(ctl, "%s", _("No disk source specified for inserting"));
        goto cleanup;
    }

    if (flags & VIR_DOMAIN_AFFECT_CONFIG)
        doc = virDomainGetXMLDesc(dom, VIR_DOMAIN_XML_INACTIVE);
    else
        doc = virDomainGetXMLDesc(dom, 0);
    if (!doc)
        goto cleanup;

    if (!(disk_node = vshFindDisk(doc, path, VSH_FIND_DISK_CHANGEABLE)))
        goto cleanup;

    if (!(disk_xml = vshPrepareDiskXML(disk_node, source, path, prepare_type)))
        goto cleanup;

    if (virDomainUpdateDeviceFlags(dom, disk_xml, flags) != 0) {
        vshError(ctl, _("Failed to complete action %s on media"), action);
        goto cleanup;
    }

    vshPrint(ctl, _("succeeded to complete action %s on media\n"), action);
    ret = true;

cleanup:
    VIR_FREE(doc);
    xmlFreeNode(disk_node);
    VIR_FREE(disk_xml);
    if (dom)
        virDomainFree(dom);
    return ret;
}

15700 15701 15702 15703
/*
 * "cpu-compare" command
 */
static const vshCmdInfo info_cpu_compare[] = {
15704 15705
    {"help", N_("compare host CPU with a CPU described by an XML file")},
    {"desc", N_("compare CPU with host CPU")},
15706 15707 15708 15709
    {NULL, NULL}
};

static const vshCmdOptDef opts_cpu_compare[] = {
15710
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing an XML CPU description")},
15711 15712 15713
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
15714
static bool
15715 15716
cmdCPUCompare(vshControl *ctl, const vshCmd *cmd)
{
15717
    const char *from = NULL;
15718
    bool ret = false;
15719 15720
    char *buffer;
    int result;
15721 15722 15723 15724 15725 15726
    const char *snippet;

    xmlDocPtr xml = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlBufferPtr xml_buf = NULL;
    xmlNodePtr node;
15727

15728
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
15729
        return false;
15730

15731
    if (vshCommandOptString(cmd, "file", &from) <= 0)
E
Eric Blake 已提交
15732
        return false;
15733

15734 15735 15736
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) {
        vshError(ctl, _("Failed to read file '%s' to compare"),
                 from);
E
Eric Blake 已提交
15737
        return false;
15738
    }
15739

15740 15741 15742 15743 15744 15745 15746 15747 15748 15749 15750 15751 15752 15753 15754 15755 15756 15757 15758 15759 15760 15761 15762 15763 15764
    /* try to extract the CPU element from as it would appear in a domain XML*/
    if (!(xml = virXMLParseStringCtxt(buffer, from, &ctxt)))
        goto cleanup;

    if ((node = virXPathNode("/cpu|"
                             "/domain/cpu|"
                              "/capabilities/host/cpu", ctxt))) {
        if (!(xml_buf = xmlBufferCreate())) {
            vshError(ctl, _("Can't create XML buffer to extract CPU element."));
            goto cleanup;
        }

        if (xmlNodeDump(xml_buf, xml, node, 0, 0) < 0) {
            vshError(ctl, _("Failed to extract CPU element snippet from domain XML."));
            goto cleanup;
        }

        snippet = (const char *) xmlBufferContent(xml_buf);
    } else {
        vshError(ctl, _("File '%s' does not contain a <cpu> element or is not "
                        "a valid domain or capabilities XML"), from);
        goto cleanup;
    }

    result = virConnectCompareCPU(ctl->conn, snippet, 0);
15765 15766 15767 15768 15769

    switch (result) {
    case VIR_CPU_COMPARE_INCOMPATIBLE:
        vshPrint(ctl, _("CPU described in %s is incompatible with host CPU\n"),
                 from);
15770
        goto cleanup;
15771 15772 15773 15774 15775 15776 15777 15778 15779 15780 15781 15782 15783 15784 15785
        break;

    case VIR_CPU_COMPARE_IDENTICAL:
        vshPrint(ctl, _("CPU described in %s is identical to host CPU\n"),
                 from);
        break;

    case VIR_CPU_COMPARE_SUPERSET:
        vshPrint(ctl, _("Host CPU is a superset of CPU described in %s\n"),
                 from);
        break;

    case VIR_CPU_COMPARE_ERROR:
    default:
        vshError(ctl, _("Failed to compare host CPU with %s"), from);
15786
        goto cleanup;
15787 15788
    }

15789 15790 15791 15792 15793 15794 15795 15796
    ret = true;

cleanup:
    VIR_FREE(buffer);
    xmlBufferFree(xml_buf);
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml);

15797 15798 15799
    return ret;
}

15800 15801 15802 15803
/*
 * "cpu-baseline" command
 */
static const vshCmdInfo info_cpu_baseline[] = {
15804 15805
    {"help", N_("compute baseline CPU")},
    {"desc", N_("Compute baseline CPU for a set of given CPUs.")},
15806 15807 15808 15809
    {NULL, NULL}
};

static const vshCmdOptDef opts_cpu_baseline[] = {
15810
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing XML CPU descriptions")},
15811 15812 15813
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
15814
static bool
15815 15816
cmdCPUBaseline(vshControl *ctl, const vshCmd *cmd)
{
15817
    const char *from = NULL;
15818
    bool ret = false;
15819 15820 15821
    char *buffer;
    char *result = NULL;
    const char **list = NULL;
15822 15823 15824 15825
    int count = 0;

    xmlDocPtr xml = NULL;
    xmlNodePtr *node_list = NULL;
15826
    xmlXPathContextPtr ctxt = NULL;
15827 15828 15829
    xmlBufferPtr xml_buf = NULL;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    int i;
15830

15831
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
15832
        return false;
15833

15834
    if (vshCommandOptString(cmd, "file", &from) <= 0)
E
Eric Blake 已提交
15835
        return false;
15836 15837

    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
E
Eric Blake 已提交
15838
        return false;
15839

E
Eric Blake 已提交
15840
    /* add a separate container around the xml */
15841 15842
    virBufferStrcat(&buf, "<container>", buffer, "</container>", NULL);
    if (virBufferError(&buf))
15843 15844
        goto no_memory;

15845 15846 15847 15848 15849 15850 15851 15852 15853 15854 15855 15856 15857
    VIR_FREE(buffer);
    buffer = virBufferContentAndReset(&buf);


    if (!(xml = virXMLParseStringCtxt(buffer, from, &ctxt)))
        goto cleanup;

    if ((count = virXPathNodeSet("//cpu[not(ancestor::cpus)]",
                                 ctxt, &node_list)) == -1)
        goto cleanup;

    if (count == 0) {
        vshError(ctl, _("No host CPU specified in '%s'"), from);
15858 15859 15860
        goto cleanup;
    }

15861
    list = vshCalloc(ctl, count, sizeof(const char *));
15862

15863
    if (!(xml_buf = xmlBufferCreate()))
15864 15865
        goto no_memory;

15866 15867
    for (i = 0; i < count; i++) {
        xmlBufferEmpty(xml_buf);
15868

15869 15870 15871
        if (xmlNodeDump(xml_buf, xml,  node_list[i], 0, 0) < 0) {
            vshError(ctl, _("Failed to extract <cpu> element"));
            goto cleanup;
15872 15873
        }

15874
        list[i] = vshStrdup(ctl, (const char *)xmlBufferContent(xml_buf));
15875 15876 15877 15878
    }

    result = virConnectBaselineCPU(ctl->conn, list, count, 0);

15879
    if (result) {
15880
        vshPrint(ctl, "%s", result);
15881 15882
        ret = true;
    }
15883 15884 15885

cleanup:
    xmlXPathFreeContext(ctxt);
15886 15887
    xmlFreeDoc(xml);
    xmlBufferFree(xml_buf);
15888
    VIR_FREE(result);
E
Eric Blake 已提交
15889
    if (list != NULL && count > 0) {
15890
        for (i = 0; i < count; i++)
15891 15892 15893 15894 15895 15896 15897 15898 15899
            VIR_FREE(list[i]);
    }
    VIR_FREE(list);
    VIR_FREE(buffer);

    return ret;

no_memory:
    vshError(ctl, "%s", _("Out of memory"));
E
Eric Blake 已提交
15900
    ret = false;
15901
    goto cleanup;
15902 15903
}

15904 15905 15906 15907 15908 15909 15910 15911 15912 15913
/* Common code for the edit / net-edit / pool-edit functions which follow. */
static char *
editWriteToTempFile (vshControl *ctl, const char *doc)
{
    char *ret;
    const char *tmpdir;
    int fd;

    tmpdir = getenv ("TMPDIR");
    if (!tmpdir) tmpdir = "/tmp";
15914 15915 15916 15917
    if (virAsprintf(&ret, "%s/virshXXXXXX.xml", tmpdir) < 0) {
        vshError(ctl, "%s", _("out of memory"));
        return NULL;
    }
15918
    fd = mkstemps(ret, 4);
15919
    if (fd == -1) {
15920
        vshError(ctl, _("mkstemps: failed to create temporary file: %s"),
15921
                 strerror(errno));
15922
        VIR_FREE(ret);
15923 15924 15925 15926
        return NULL;
    }

    if (safewrite (fd, doc, strlen (doc)) == -1) {
15927 15928
        vshError(ctl, _("write: %s: failed to write to temporary file: %s"),
                 ret, strerror(errno));
S
Stefan Berger 已提交
15929
        VIR_FORCE_CLOSE(fd);
15930
        unlink (ret);
15931
        VIR_FREE(ret);
15932 15933
        return NULL;
    }
S
Stefan Berger 已提交
15934
    if (VIR_CLOSE(fd) < 0) {
15935 15936
        vshError(ctl, _("close: %s: failed to write or close temporary file: %s"),
                 ret, strerror(errno));
15937
        unlink (ret);
15938
        VIR_FREE(ret);
15939 15940 15941 15942 15943 15944 15945 15946 15947 15948 15949 15950 15951 15952 15953
        return NULL;
    }

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

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

static int
editFile (vshControl *ctl, const char *filename)
{
    const char *editor;
E
Eric Blake 已提交
15954 15955 15956 15957
    virCommandPtr cmd;
    int ret = -1;
    int outfd = STDOUT_FILENO;
    int errfd = STDERR_FILENO;
15958

15959
    editor = getenv ("VISUAL");
E
Eric Blake 已提交
15960 15961 15962 15963
    if (!editor)
        editor = getenv ("EDITOR");
    if (!editor)
        editor = "vi"; /* could be cruel & default to ed(1) here */
15964

15965 15966 15967 15968 15969
    /* Check that filename doesn't contain shell meta-characters, and
     * if it does, refuse to run.  Follow the Unix conventions for
     * EDITOR: the user can intentionally specify command options, so
     * we don't protect any shell metacharacters there.  Lots more
     * than virsh will misbehave if EDITOR has bogus contents (which
E
Eric Blake 已提交
15970 15971
     * is why sudo scrubs it by default).  Conversely, if the editor
     * is safe, we can run it directly rather than wasting a shell.
15972
     */
E
Eric Blake 已提交
15973 15974 15975 15976 15977 15978 15979 15980 15981 15982 15983 15984
    if (strspn (editor, ACCEPTED_CHARS) != strlen (editor)) {
        if (strspn (filename, ACCEPTED_CHARS) != strlen (filename)) {
            vshError(ctl,
                     _("%s: temporary filename contains shell meta or other "
                       "unacceptable characters (is $TMPDIR wrong?)"),
                     filename);
            return -1;
        }
        cmd = virCommandNewArgList("sh", "-c", NULL);
        virCommandAddArgFormat(cmd, "%s %s", editor, filename);
    } else {
        cmd = virCommandNewArgList(editor, filename, NULL);
15985 15986
    }

E
Eric Blake 已提交
15987 15988 15989 15990 15991 15992 15993
    virCommandSetInputFD(cmd, STDIN_FILENO);
    virCommandSetOutputFD(cmd, &outfd);
    virCommandSetErrorFD(cmd, &errfd);
    if (virCommandRunAsync(cmd, NULL) < 0 ||
        virCommandWait(cmd, NULL) < 0) {
        virshReportError(ctl);
        goto cleanup;
15994
    }
E
Eric Blake 已提交
15995
    ret = 0;
15996

E
Eric Blake 已提交
15997 15998 15999
cleanup:
    virCommandFree(cmd);
    return ret;
16000 16001 16002 16003 16004 16005 16006
}

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

E
Eric Blake 已提交
16007
    if (virFileReadAll(filename, VIRSH_MAX_XML_FILE, &ret) == -1) {
16008
        vshError(ctl,
16009
                 _("%s: failed to read temporary file: %s"),
16010
                 filename, strerror(errno));
16011 16012 16013 16014 16015
        return NULL;
    }
    return ret;
}

16016

P
Paolo Bonzini 已提交
16017 16018 16019 16020
/*
 * "cd" command
 */
static const vshCmdInfo info_cd[] = {
16021 16022
    {"help", N_("change the current directory")},
    {"desc", N_("Change the current directory.")},
P
Paolo Bonzini 已提交
16023 16024 16025 16026
    {NULL, NULL}
};

static const vshCmdOptDef opts_cd[] = {
16027
    {"dir", VSH_OT_DATA, 0, N_("directory to switch to (default: home or else root)")},
P
Paolo Bonzini 已提交
16028 16029 16030
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
16031
static bool
16032
cmdCd(vshControl *ctl, const vshCmd *cmd)
P
Paolo Bonzini 已提交
16033
{
16034
    const char *dir = NULL;
16035
    char *dir_malloced = NULL;
E
Eric Blake 已提交
16036
    bool ret = true;
P
Paolo Bonzini 已提交
16037 16038

    if (!ctl->imode) {
16039
        vshError(ctl, "%s", _("cd: command valid only in interactive mode"));
E
Eric Blake 已提交
16040
        return false;
P
Paolo Bonzini 已提交
16041 16042
    }

16043
    if (vshCommandOptString(cmd, "dir", &dir) <= 0) {
16044
        dir = dir_malloced = virGetUserDirectory();
P
Paolo Bonzini 已提交
16045 16046 16047 16048
    }
    if (!dir)
        dir = "/";

P
Phil Petty 已提交
16049
    if (chdir(dir) == -1) {
16050
        vshError(ctl, _("cd: %s: %s"), strerror(errno), dir);
E
Eric Blake 已提交
16051
        ret = false;
P
Paolo Bonzini 已提交
16052 16053
    }

16054
    VIR_FREE(dir_malloced);
P
Phil Petty 已提交
16055
    return ret;
P
Paolo Bonzini 已提交
16056 16057 16058 16059 16060 16061
}

/*
 * "pwd" command
 */
static const vshCmdInfo info_pwd[] = {
16062 16063
    {"help", N_("print the current directory")},
    {"desc", N_("Print the current directory.")},
P
Paolo Bonzini 已提交
16064 16065 16066
    {NULL, NULL}
};

E
Eric Blake 已提交
16067
static bool
P
Paolo Bonzini 已提交
16068 16069 16070
cmdPwd(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    char *cwd;
16071
    bool ret = true;
P
Paolo Bonzini 已提交
16072

16073 16074
    cwd = getcwd(NULL, 0);
    if (!cwd) {
16075 16076
        vshError(ctl, _("pwd: cannot get current directory: %s"),
                 strerror(errno));
16077 16078
        ret = false;
    } else {
P
Paolo Bonzini 已提交
16079
        vshPrint (ctl, _("%s\n"), cwd);
16080 16081
        VIR_FREE(cwd);
    }
P
Paolo Bonzini 已提交
16082

16083
    return ret;
P
Paolo Bonzini 已提交
16084 16085
}

E
Eric Blake 已提交
16086 16087 16088 16089 16090 16091 16092 16093 16094 16095 16096 16097
/*
 * "echo" command
 */
static const vshCmdInfo info_echo[] = {
    {"help", N_("echo arguments")},
    {"desc", N_("Echo back arguments, possibly with quoting.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_echo[] = {
    {"shell", VSH_OT_BOOL, 0, N_("escape for shell use")},
    {"xml", VSH_OT_BOOL, 0, N_("escape for XML use")},
E
Eric Blake 已提交
16098
    {"str", VSH_OT_ALIAS, 0, "string"},
16099
    {"string", VSH_OT_ARGV, 0, N_("arguments to echo")},
E
Eric Blake 已提交
16100 16101 16102 16103 16104 16105
    {NULL, 0, 0, NULL}
};

/* Exists mainly for debugging virsh, but also handy for adding back
 * quotes for later evaluation.
 */
E
Eric Blake 已提交
16106
static bool
16107
cmdEcho (vshControl *ctl, const vshCmd *cmd)
E
Eric Blake 已提交
16108 16109 16110 16111
{
    bool shell = false;
    bool xml = false;
    int count = 0;
16112
    const vshCmdOpt *opt = NULL;
E
Eric Blake 已提交
16113 16114 16115 16116 16117 16118 16119 16120
    char *arg;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    if (vshCommandOptBool(cmd, "shell"))
        shell = true;
    if (vshCommandOptBool(cmd, "xml"))
        xml = true;

16121
    while ((opt = vshCommandOptArgv(cmd, opt))) {
16122 16123
        char *str;
        virBuffer xmlbuf = VIR_BUFFER_INITIALIZER;
E
Eric Blake 已提交
16124

16125
        arg = opt->data;
16126

E
Eric Blake 已提交
16127 16128
        if (count)
            virBufferAddChar(&buf, ' ');
16129

E
Eric Blake 已提交
16130
        if (xml) {
16131 16132 16133 16134
            virBufferEscapeString(&xmlbuf, "%s", arg);
            if (virBufferError(&buf)) {
                vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
                return false;
E
Eric Blake 已提交
16135
            }
16136 16137 16138
            str = virBufferContentAndReset(&xmlbuf);
        } else {
            str = vshStrdup(ctl, arg);
E
Eric Blake 已提交
16139
        }
16140 16141 16142 16143 16144

        if (shell)
            virBufferEscapeShell(&buf, str);
        else
            virBufferAdd(&buf, str, -1);
E
Eric Blake 已提交
16145
        count++;
16146
        VIR_FREE(str);
E
Eric Blake 已提交
16147 16148 16149 16150
    }

    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
E
Eric Blake 已提交
16151
        return false;
E
Eric Blake 已提交
16152 16153 16154 16155 16156
    }
    arg = virBufferContentAndReset(&buf);
    if (arg)
        vshPrint(ctl, "%s", arg);
    VIR_FREE(arg);
E
Eric Blake 已提交
16157
    return true;
E
Eric Blake 已提交
16158 16159
}

16160 16161 16162 16163
/*
 * "edit" command
 */
static const vshCmdInfo info_edit[] = {
16164 16165
    {"help", N_("edit XML configuration for a domain")},
    {"desc", N_("Edit the XML configuration for a domain.")},
16166 16167 16168 16169
    {NULL, NULL}
};

static const vshCmdOptDef opts_edit[] = {
16170
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
16171 16172 16173
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
16174
static bool
16175
cmdEdit(vshControl *ctl, const vshCmd *cmd)
16176
{
E
Eric Blake 已提交
16177
    bool ret = false;
16178
    virDomainPtr dom = NULL;
16179
    virDomainPtr dom_edited = NULL;
E
Eric Blake 已提交
16180
    unsigned int flags = VIR_DOMAIN_XML_SECURE | VIR_DOMAIN_XML_INACTIVE;
16181

16182
    if (!vshConnectionUsability(ctl, ctl->conn))
16183 16184
        goto cleanup;

16185
    dom = vshCommandOptDomain(ctl, cmd, NULL);
16186 16187 16188
    if (dom == NULL)
        goto cleanup;

W
Wen Congyang 已提交
16189 16190 16191 16192 16193 16194 16195 16196 16197 16198 16199
#define EDIT_GET_XML virDomainGetXMLDesc(dom, flags)
#define EDIT_NOT_CHANGED \
    vshPrint(ctl, _("Domain %s XML configuration not changed.\n"),  \
             virDomainGetName (dom));                               \
    ret = true; goto edit_cleanup;
#define EDIT_DEFINE \
    (dom_edited = virDomainDefineXML(ctl->conn, doc_edited))
#define EDIT_FREE \
    if (dom_edited) \
        virDomainFree(dom_edited);
#include "virsh-edit.c"
16200

16201
    vshPrint(ctl, _("Domain %s XML configuration edited.\n"),
16202
             virDomainGetName(dom_edited));
16203

E
Eric Blake 已提交
16204
    ret = true;
16205 16206 16207

 cleanup:
    if (dom)
16208 16209 16210
        virDomainFree(dom);
    if (dom_edited)
        virDomainFree(dom_edited);
16211 16212 16213 16214

    return ret;
}

16215

16216 16217 16218 16219
/*
 * "net-edit" command
 */
static const vshCmdInfo info_network_edit[] = {
16220 16221
    {"help", N_("edit XML configuration for a network")},
    {"desc", N_("Edit the XML configuration for a network.")},
16222 16223 16224 16225
    {NULL, NULL}
};

static const vshCmdOptDef opts_network_edit[] = {
16226
    {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")},
16227 16228 16229
    {NULL, 0, 0, NULL}
};

16230 16231 16232 16233 16234 16235 16236 16237 16238 16239 16240 16241 16242 16243 16244 16245 16246
static char *vshNetworkGetXMLDesc(virNetworkPtr network)
{
    unsigned int flags = VIR_NETWORK_XML_INACTIVE;
    char *doc = virNetworkGetXMLDesc(network, flags);

    if (!doc && last_error->code == VIR_ERR_INVALID_ARG) {
        /* The server side libvirt doesn't support
         * VIR_NETWORK_XML_INACTIVE, so retry without it.
         */
        virFreeError(last_error);
        last_error = NULL;
        flags &= ~VIR_NETWORK_XML_INACTIVE;
        doc = virNetworkGetXMLDesc(network, flags);
    }
    return doc;
}

16247 16248 16249 16250 16251 16252 16253 16254 16255 16256 16257 16258 16259 16260
static bool
cmdNetworkEdit(vshControl *ctl, const vshCmd *cmd)
{
    bool ret = false;
    virNetworkPtr network = NULL;
    virNetworkPtr network_edited = NULL;

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

    network = vshCommandOptNetwork(ctl, cmd, NULL);
    if (network == NULL)
        goto cleanup;

16261
#define EDIT_GET_XML vshNetworkGetXMLDesc(network)
W
Wen Congyang 已提交
16262 16263 16264 16265 16266 16267 16268 16269 16270 16271
#define EDIT_NOT_CHANGED \
    vshPrint(ctl, _("Network %s XML configuration not changed.\n"), \
             virNetworkGetName (network));                          \
    ret = true; goto edit_cleanup;
#define EDIT_DEFINE \
    (network_edited = virNetworkDefineXML(ctl->conn, doc_edited))
#define EDIT_FREE \
    if (network_edited) \
        virNetworkFree(network_edited);
#include "virsh-edit.c"
16272 16273

    vshPrint(ctl, _("Network %s XML configuration edited.\n"),
16274
             virNetworkGetName(network_edited));
16275 16276 16277 16278 16279 16280 16281 16282 16283 16284 16285

    ret = true;

 cleanup:
    if (network)
        virNetworkFree(network);
    if (network_edited)
        virNetworkFree(network_edited);

    return ret;
}
16286 16287 16288 16289 16290

/*
 * "pool-edit" command
 */
static const vshCmdInfo info_pool_edit[] = {
16291 16292
    {"help", N_("edit XML configuration for a storage pool")},
    {"desc", N_("Edit the XML configuration for a storage pool.")},
16293 16294 16295 16296
    {NULL, NULL}
};

static const vshCmdOptDef opts_pool_edit[] = {
16297
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, N_("pool name or uuid")},
16298 16299 16300
    {NULL, 0, 0, NULL}
};

16301 16302 16303 16304 16305 16306
static bool
cmdPoolEdit(vshControl *ctl, const vshCmd *cmd)
{
    bool ret = false;
    virStoragePoolPtr pool = NULL;
    virStoragePoolPtr pool_edited = NULL;
16307 16308
    unsigned int flags = VIR_STORAGE_XML_INACTIVE;
    char *tmp_desc = NULL;
16309 16310 16311 16312 16313 16314 16315 16316

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

    pool = vshCommandOptPool(ctl, cmd, "pool", NULL);
    if (pool == NULL)
        goto cleanup;

16317 16318 16319 16320 16321 16322 16323 16324 16325 16326 16327 16328 16329
    /* Some old daemons don't support _INACTIVE flag */
    if (!(tmp_desc = virStoragePoolGetXMLDesc(pool, flags))) {
        if (last_error->code == VIR_ERR_INVALID_ARG) {
            flags &= ~VIR_STORAGE_XML_INACTIVE;
            virFreeError(last_error);
            last_error = NULL;
        } else {
            goto cleanup;
        }
    } else {
        VIR_FREE(tmp_desc);
    }

W
Wen Congyang 已提交
16330 16331 16332 16333 16334 16335 16336 16337 16338 16339 16340
#define EDIT_GET_XML virStoragePoolGetXMLDesc(pool, flags)
#define EDIT_NOT_CHANGED \
    vshPrint(ctl, _("Pool %s XML configuration not changed.\n"),    \
             virStoragePoolGetName (pool));                         \
    ret = true; goto edit_cleanup;
#define EDIT_DEFINE \
    (pool_edited = virStoragePoolDefineXML(ctl->conn, doc_edited, 0))
#define EDIT_FREE \
    if (pool_edited)    \
        virStoragePoolFree(pool_edited);
#include "virsh-edit.c"
16341 16342

    vshPrint(ctl, _("Pool %s XML configuration edited.\n"),
16343
             virStoragePoolGetName(pool_edited));
16344 16345 16346 16347 16348 16349 16350 16351 16352 16353 16354

    ret = true;

 cleanup:
    if (pool)
        virStoragePoolFree(pool);
    if (pool_edited)
        virStoragePoolFree(pool_edited);

    return ret;
}
16355

K
Karel Zak 已提交
16356 16357 16358
/*
 * "quit" command
 */
16359
static const vshCmdInfo info_quit[] = {
16360
    {"help", N_("quit this interactive terminal")},
16361
    {"desc", ""},
16362
    {NULL, NULL}
K
Karel Zak 已提交
16363 16364
};

E
Eric Blake 已提交
16365
static bool
16366
cmdQuit(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
16367
{
E
Eric Blake 已提交
16368 16369
    ctl->imode = false;
    return true;
K
Karel Zak 已提交
16370 16371
}

16372 16373 16374 16375 16376 16377 16378
/* Helper for snapshot-create and snapshot-create-as */
static bool
vshSnapshotCreate(vshControl *ctl, virDomainPtr dom, const char *buffer,
                  unsigned int flags, const char *from)
{
    bool ret = false;
    virDomainSnapshotPtr snapshot;
16379
    bool halt = false;
16380 16381 16382
    char *doc = NULL;
    xmlDocPtr xml = NULL;
    xmlXPathContextPtr ctxt = NULL;
E
Eric Blake 已提交
16383
    const char *name = NULL;
16384 16385

    snapshot = virDomainSnapshotCreateXML(dom, buffer, flags);
16386 16387 16388 16389 16390 16391 16392 16393 16394 16395 16396 16397 16398 16399 16400 16401 16402 16403 16404 16405 16406 16407 16408 16409

    /* Emulate --halt on older servers.  */
    if (!snapshot && last_error->code == VIR_ERR_INVALID_ARG &&
        (flags & VIR_DOMAIN_SNAPSHOT_CREATE_HALT)) {
        int persistent;

        virFreeError(last_error);
        last_error = NULL;
        persistent = virDomainIsPersistent(dom);
        if (persistent < 0) {
            virshReportError(ctl);
            goto cleanup;
        }
        if (!persistent) {
            vshError(ctl, "%s",
                     _("cannot halt after snapshot of transient domain"));
            goto cleanup;
        }
        if (virDomainIsActive(dom) == 1)
            halt = true;
        flags &= ~VIR_DOMAIN_SNAPSHOT_CREATE_HALT;
        snapshot = virDomainSnapshotCreateXML(dom, buffer, flags);
    }

16410 16411 16412
    if (snapshot == NULL)
        goto cleanup;

16413 16414 16415 16416 16417
    if (halt && virDomainDestroy(dom) < 0) {
        virshReportError(ctl);
        goto cleanup;
    }

E
Eric Blake 已提交
16418
    name = virDomainSnapshotGetName(snapshot);
16419
    if (!name) {
E
Eric Blake 已提交
16420
        vshError(ctl, "%s", _("Could not get snapshot name"));
16421 16422 16423 16424 16425 16426 16427 16428 16429 16430 16431 16432 16433 16434 16435 16436 16437 16438 16439
        goto cleanup;
    }

    if (from)
        vshPrint(ctl, _("Domain snapshot %s created from '%s'"), name, from);
    else
        vshPrint(ctl, _("Domain snapshot %s created"), name);

    ret = true;

cleanup:
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml);
    if (snapshot)
        virDomainSnapshotFree(snapshot);
    VIR_FREE(doc);
    return ret;
}

16440 16441 16442 16443
/*
 * "snapshot-create" command
 */
static const vshCmdInfo info_snapshot_create[] = {
E
Eric Blake 已提交
16444 16445
    {"help", N_("Create a snapshot from XML")},
    {"desc", N_("Create a snapshot (disk and RAM) from XML")},
16446 16447 16448 16449 16450 16451
    {NULL, NULL}
};

static const vshCmdOptDef opts_snapshot_create[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"xmlfile", VSH_OT_DATA, 0, N_("domain snapshot XML")},
16452 16453 16454
    {"redefine", VSH_OT_BOOL, 0, N_("redefine metadata for existing snapshot")},
    {"current", VSH_OT_BOOL, 0, N_("with redefine, set current snapshot")},
    {"no-metadata", VSH_OT_BOOL, 0, N_("take snapshot but create no metadata")},
16455
    {"halt", VSH_OT_BOOL, 0, N_("halt domain after snapshot is created")},
16456
    {"disk-only", VSH_OT_BOOL, 0, N_("capture disk state but not vm state")},
16457
    {"reuse-external", VSH_OT_BOOL, 0, N_("reuse any existing external files")},
16458
    {"quiesce", VSH_OT_BOOL, 0, N_("quiesce guest's file systems")},
E
Eric Blake 已提交
16459
    {"atomic", VSH_OT_BOOL, 0, N_("require atomic operation")},
16460 16461 16462
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
16463
static bool
16464 16465 16466
cmdSnapshotCreate(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
E
Eric Blake 已提交
16467
    bool ret = false;
16468
    const char *from = NULL;
16469
    char *buffer = NULL;
16470 16471 16472 16473 16474 16475 16476 16477
    unsigned int flags = 0;

    if (vshCommandOptBool(cmd, "redefine"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE;
    if (vshCommandOptBool(cmd, "current"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT;
    if (vshCommandOptBool(cmd, "no-metadata"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA;
16478 16479
    if (vshCommandOptBool(cmd, "halt"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_HALT;
16480 16481
    if (vshCommandOptBool(cmd, "disk-only"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY;
16482 16483
    if (vshCommandOptBool(cmd, "reuse-external"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT;
16484 16485
    if (vshCommandOptBool(cmd, "quiesce"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE;
E
Eric Blake 已提交
16486 16487
    if (vshCommandOptBool(cmd, "atomic"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC;
16488

16489
    if (!vshConnectionUsability(ctl, ctl->conn))
16490 16491 16492 16493 16494 16495
        goto cleanup;

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

16496
    if (vshCommandOptString(cmd, "xmlfile", &from) <= 0)
E
Eric Blake 已提交
16497
        buffer = vshStrdup(ctl, "<domainsnapshot/>");
16498 16499 16500 16501 16502 16503 16504 16505 16506 16507 16508 16509 16510 16511 16512
    else {
        if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) {
            /* we have to report the error here because during cleanup
             * we'll run through virDomainFree(), which loses the
             * last error
             */
            virshReportError(ctl);
            goto cleanup;
        }
    }
    if (buffer == NULL) {
        vshError(ctl, "%s", _("Out of memory"));
        goto cleanup;
    }

16513
    ret = vshSnapshotCreate(ctl, dom, buffer, flags, from);
16514 16515 16516 16517 16518 16519 16520 16521 16522

cleanup:
    VIR_FREE(buffer);
    if (dom)
        virDomainFree(dom);

    return ret;
}

16523 16524 16525
/*
 * "snapshot-create-as" command
 */
16526 16527 16528 16529 16530 16531 16532 16533 16534 16535 16536 16537 16538 16539 16540 16541 16542 16543
static int
vshParseSnapshotDiskspec(vshControl *ctl, virBufferPtr buf, const char *str)
{
    int ret = -1;
    char *name = NULL;
    char *snapshot = NULL;
    char *driver = NULL;
    char *file = NULL;
    char *spec = vshStrdup(ctl, str);
    char *tmp = spec;
    size_t len = strlen(str);

    if (*str == ',')
        goto cleanup;
    name = tmp;
    while ((tmp = strchr(tmp, ','))) {
        if (tmp[1] == ',') {
            /* Recognize ,, as an escape for a literal comma */
16544
            memmove(&tmp[1], &tmp[2], len - (tmp - spec) - 2 + 1);
16545 16546 16547 16548 16549 16550 16551 16552 16553 16554 16555 16556 16557 16558 16559 16560 16561 16562 16563 16564 16565 16566 16567 16568 16569 16570 16571 16572 16573 16574 16575 16576 16577 16578 16579 16580 16581
            len--;
            tmp++;
            continue;
        }
        /* Terminate previous string, look for next recognized one */
        *tmp++ = '\0';
        if (!snapshot && STRPREFIX(tmp, "snapshot="))
            snapshot = tmp + strlen("snapshot=");
        else if (!driver && STRPREFIX(tmp, "driver="))
            driver = tmp + strlen("driver=");
        else if (!file && STRPREFIX(tmp, "file="))
            file = tmp + strlen("file=");
        else
            goto cleanup;
    }

    virBufferEscapeString(buf, "    <disk name='%s'", name);
    if (snapshot)
        virBufferAsprintf(buf, " snapshot='%s'", snapshot);
    if (driver || file) {
        virBufferAddLit(buf, ">\n");
        if (driver)
            virBufferAsprintf(buf, "      <driver type='%s'/>\n", driver);
        if (file)
            virBufferEscapeString(buf, "      <source file='%s'/>\n", file);
        virBufferAddLit(buf, "    </disk>\n");
    } else {
        virBufferAddLit(buf, "/>\n");
    }
    ret = 0;
cleanup:
    if (ret < 0)
        vshError(ctl, _("unable to parse diskspec: %s"), str);
    VIR_FREE(spec);
    return ret;
}

16582 16583 16584 16585 16586 16587 16588 16589 16590 16591
static const vshCmdInfo info_snapshot_create_as[] = {
    {"help", N_("Create a snapshot from a set of args")},
    {"desc", N_("Create a snapshot (disk and RAM) from arguments")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_snapshot_create_as[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"name", VSH_OT_DATA, 0, N_("name of snapshot")},
    {"description", VSH_OT_DATA, 0, N_("description of snapshot")},
E
Eric Blake 已提交
16592
    {"print-xml", VSH_OT_BOOL, 0, N_("print XML document rather than create")},
16593
    {"no-metadata", VSH_OT_BOOL, 0, N_("take snapshot but create no metadata")},
16594
    {"halt", VSH_OT_BOOL, 0, N_("halt domain after snapshot is created")},
16595
    {"disk-only", VSH_OT_BOOL, 0, N_("capture disk state but not vm state")},
16596
    {"reuse-external", VSH_OT_BOOL, 0, N_("reuse any existing external files")},
16597
    {"quiesce", VSH_OT_BOOL, 0, N_("quiesce guest's file systems")},
E
Eric Blake 已提交
16598
    {"atomic", VSH_OT_BOOL, 0, N_("require atomic operation")},
16599 16600
    {"diskspec", VSH_OT_ARGV, 0,
     N_("disk attributes: disk[,snapshot=type][,driver=type][,file=name]")},
16601 16602 16603 16604 16605 16606 16607 16608 16609 16610 16611 16612
    {NULL, 0, 0, NULL}
};

static bool
cmdSnapshotCreateAs(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
    bool ret = false;
    char *buffer = NULL;
    const char *name = NULL;
    const char *desc = NULL;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
16613
    unsigned int flags = 0;
16614
    const vshCmdOpt *opt = NULL;
16615 16616 16617

    if (vshCommandOptBool(cmd, "no-metadata"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA;
16618 16619
    if (vshCommandOptBool(cmd, "halt"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_HALT;
16620 16621
    if (vshCommandOptBool(cmd, "disk-only"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY;
16622 16623
    if (vshCommandOptBool(cmd, "reuse-external"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT;
16624 16625
    if (vshCommandOptBool(cmd, "quiesce"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE;
E
Eric Blake 已提交
16626 16627
    if (vshCommandOptBool(cmd, "atomic"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC;
16628 16629 16630 16631 16632 16633 16634 16635 16636 16637 16638 16639 16640 16641 16642 16643

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

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

    if (vshCommandOptString(cmd, "name", &name) < 0 ||
        vshCommandOptString(cmd, "description", &desc) < 0) {
        vshError(ctl, _("argument must not be empty"));
        goto cleanup;
    }

    virBufferAddLit(&buf, "<domainsnapshot>\n");
    if (name)
16644
        virBufferEscapeString(&buf, "  <name>%s</name>\n", name);
16645
    if (desc)
16646
        virBufferEscapeString(&buf, "  <description>%s</description>\n", desc);
16647 16648 16649 16650 16651 16652 16653 16654 16655 16656
    if (vshCommandOptBool(cmd, "diskspec")) {
        virBufferAddLit(&buf, "  <disks>\n");
        while ((opt = vshCommandOptArgv(cmd, opt))) {
            if (vshParseSnapshotDiskspec(ctl, &buf, opt->data) < 0) {
                virBufferFreeAndReset(&buf);
                goto cleanup;
            }
        }
        virBufferAddLit(&buf, "  </disks>\n");
    }
16657 16658 16659 16660 16661 16662 16663 16664
    virBufferAddLit(&buf, "</domainsnapshot>\n");

    buffer = virBufferContentAndReset(&buf);
    if (buffer == NULL) {
        vshError(ctl, "%s", _("Out of memory"));
        goto cleanup;
    }

E
Eric Blake 已提交
16665 16666 16667 16668 16669 16670
    if (vshCommandOptBool(cmd, "print-xml")) {
        vshPrint(ctl, "%s\n",  buffer);
        ret = true;
        goto cleanup;
    }

16671
    ret = vshSnapshotCreate(ctl, dom, buffer, flags, NULL);
16672 16673 16674 16675 16676 16677 16678 16679 16680

cleanup:
    VIR_FREE(buffer);
    if (dom)
        virDomainFree(dom);

    return ret;
}

16681 16682 16683 16684 16685 16686 16687 16688 16689 16690 16691 16692 16693 16694 16695 16696 16697 16698 16699 16700 16701 16702 16703 16704 16705 16706 16707 16708 16709 16710 16711 16712 16713 16714 16715 16716 16717 16718 16719
/* Helper for resolving {--current | --ARG name} into a snapshot
 * belonging to DOM.  If EXCLUSIVE, fail if both --current and arg are
 * present.  On success, populate *SNAP and *NAME, before returning 0.
 * On failure, return -1 after issuing an error message.  */
static int
vshLookupSnapshot(vshControl *ctl, const vshCmd *cmd,
                  const char *arg, bool exclusive, virDomainPtr dom,
                  virDomainSnapshotPtr *snap, const char **name)
{
    bool current = vshCommandOptBool(cmd, "current");
    const char *snapname = NULL;

    if (vshCommandOptString(cmd, arg, &snapname) < 0) {
        vshError(ctl, _("invalid argument for --%s"), arg);
        return -1;
    }

    if (exclusive && current && snapname) {
        vshError(ctl, _("--%s and --current are mutually exclusive"), arg);
        return -1;
    }

    if (snapname) {
        *snap = virDomainSnapshotLookupByName(dom, snapname, 0);
    } else if (current) {
        *snap = virDomainSnapshotCurrent(dom, 0);
    } else {
        vshError(ctl, _("--%s or --current is required"), arg);
        return -1;
    }
    if (!*snap) {
        virshReportError(ctl);
        return -1;
    }

    *name = virDomainSnapshotGetName(*snap);
    return 0;
}

16720 16721 16722 16723 16724 16725 16726 16727 16728 16729 16730
/*
 * "snapshot-edit" command
 */
static const vshCmdInfo info_snapshot_edit[] = {
    {"help", N_("edit XML for a snapshot")},
    {"desc", N_("Edit the domain snapshot XML for a named snapshot")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_snapshot_edit[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
16731
    {"snapshotname", VSH_OT_DATA, 0, N_("snapshot name")},
16732
    {"current", VSH_OT_BOOL, 0, N_("also set edited snapshot as current")},
16733 16734
    {"rename", VSH_OT_BOOL, 0, N_("allow renaming an existing snapshot")},
    {"clone", VSH_OT_BOOL, 0, N_("allow cloning to new name")},
16735 16736 16737 16738 16739 16740 16741 16742
    {NULL, 0, 0, NULL}
};

static bool
cmdSnapshotEdit(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
    virDomainSnapshotPtr snapshot = NULL;
16743
    virDomainSnapshotPtr edited = NULL;
16744
    const char *name;
16745
    const char *edited_name;
16746 16747 16748
    bool ret = false;
    unsigned int getxml_flags = VIR_DOMAIN_XML_SECURE;
    unsigned int define_flags = VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE;
16749 16750 16751 16752 16753 16754 16755 16756
    bool rename_okay = vshCommandOptBool(cmd, "rename");
    bool clone_okay = vshCommandOptBool(cmd, "clone");

    if (rename_okay && clone_okay) {
        vshError(ctl, "%s",
                 _("--rename and --clone are mutually exclusive"));
        return false;
    }
16757

16758 16759
    if (vshCommandOptBool(cmd, "current") &&
        vshCommandOptBool(cmd, "snapshotname"))
16760 16761 16762 16763 16764 16765 16766 16767 16768
        define_flags |= VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT;

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

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

16769 16770
    if (vshLookupSnapshot(ctl, cmd, "snapshotname", false, dom,
                          &snapshot, &name) < 0)
16771 16772
        goto cleanup;

W
Wen Congyang 已提交
16773 16774 16775 16776 16777 16778 16779 16780 16781 16782 16783 16784 16785 16786 16787 16788 16789 16790 16791
#define EDIT_GET_XML \
    virDomainSnapshotGetXMLDesc(snapshot, getxml_flags)
#define EDIT_NOT_CHANGED \
    /* Depending on flags, we re-edit even if XML is unchanged.  */ \
    if (!(define_flags & VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT)) {     \
        vshPrint(ctl,                                               \
                 _("Snapshot %s XML configuration not changed.\n"), \
                 name);                                             \
        ret = true;                                                 \
        goto cleanup;                                               \
    }
#define EDIT_DEFINE \
    (strstr(doc, "<state>disk-snapshot</state>") ? \
    define_flags |= VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY : 0), \
    edited = virDomainSnapshotCreateXML(dom, doc_edited, define_flags)
#define EDIT_FREE \
    if (edited) \
        virDomainSnapshotFree(edited);
#include "virsh-edit.c"
16792

16793 16794 16795 16796 16797 16798 16799 16800 16801 16802 16803 16804 16805 16806 16807 16808 16809 16810 16811 16812 16813 16814 16815 16816
    edited_name = virDomainSnapshotGetName(edited);
    if (STREQ(name, edited_name)) {
        vshPrint(ctl, _("Snapshot %s edited.\n"), name);
    } else if (clone_okay) {
        vshPrint(ctl, _("Snapshot %s cloned to %s.\n"), name,
                 edited_name);
    } else {
        unsigned int delete_flags;

        delete_flags = VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY;
        if (virDomainSnapshotDelete(rename_okay ? snapshot : edited,
                                    delete_flags) < 0) {
            virshReportError(ctl);
            vshError(ctl, _("Failed to clean up %s"),
                     rename_okay ? name : edited_name);
            goto cleanup;
        }
        if (!rename_okay) {
            vshError(ctl, _("Must use --rename or --clone to change %s to %s"),
                     name, edited_name);
            goto cleanup;
        }
    }

16817 16818 16819
    ret = true;

cleanup:
16820 16821
    if (edited)
        virDomainSnapshotFree(edited);
16822 16823 16824 16825
    else
        vshError(ctl, _("Failed to update %s"), name);
    if (snapshot)
        virDomainSnapshotFree(snapshot);
16826 16827 16828 16829 16830
    if (dom)
        virDomainFree(dom);
    return ret;
}

16831 16832 16833 16834
/*
 * "snapshot-current" command
 */
static const vshCmdInfo info_snapshot_current[] = {
16835 16836
    {"help", N_("Get or set the current snapshot")},
    {"desc", N_("Get or set the current snapshot")},
16837 16838 16839 16840 16841
    {NULL, NULL}
};

static const vshCmdOptDef opts_snapshot_current[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
16842
    {"name", VSH_OT_BOOL, 0, N_("list the name, rather than the full xml")},
16843 16844
    {"security-info", VSH_OT_BOOL, 0,
     N_("include security sensitive information in XML dump")},
16845 16846
    {"snapshotname", VSH_OT_DATA, 0,
     N_("name of existing snapshot to make current")},
16847 16848 16849
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
16850
static bool
16851 16852 16853
cmdSnapshotCurrent(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
E
Eric Blake 已提交
16854
    bool ret = false;
16855 16856
    int current;
    virDomainSnapshotPtr snapshot = NULL;
16857
    char *xml = NULL;
16858
    const char *snapshotname = NULL;
16859
    unsigned int flags = 0;
16860
    const char *domname;
16861 16862 16863

    if (vshCommandOptBool(cmd, "security-info"))
        flags |= VIR_DOMAIN_XML_SECURE;
16864

16865
    if (!vshConnectionUsability(ctl, ctl->conn))
16866 16867
        goto cleanup;

16868
    dom = vshCommandOptDomain(ctl, cmd, &domname);
16869 16870 16871
    if (dom == NULL)
        goto cleanup;

16872 16873 16874 16875 16876 16877 16878 16879 16880 16881 16882 16883 16884 16885 16886 16887 16888 16889 16890 16891
    if (vshCommandOptString(cmd, "snapshotname", &snapshotname) < 0) {
        vshError(ctl, _("invalid snapshotname argument '%s'"), snapshotname);
        goto cleanup;
    }
    if (snapshotname) {
        virDomainSnapshotPtr snapshot2 = NULL;
        flags = (VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE |
                 VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT);

        if (vshCommandOptBool(cmd, "name")) {
            vshError(ctl, "%s",
                     _("--name and snapshotname are mutually exclusive"));
            goto cleanup;
        }
        snapshot = virDomainSnapshotLookupByName(dom, snapshotname, 0);
        if (snapshot == NULL)
            goto cleanup;
        xml = virDomainSnapshotGetXMLDesc(snapshot, VIR_DOMAIN_XML_SECURE);
        if (!xml)
            goto cleanup;
16892 16893 16894
        /* strstr is safe here, since xml came from libvirt API and not user */
        if (strstr(xml, "<state>disk-snapshot</state>"))
            flags |= VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY;
16895 16896 16897 16898 16899 16900 16901 16902 16903
        snapshot2 = virDomainSnapshotCreateXML(dom, xml, flags);
        if (snapshot2 == NULL)
            goto cleanup;
        virDomainSnapshotFree(snapshot2);
        vshPrint(ctl, _("Snapshot %s set as current"), snapshotname);
        ret = true;
        goto cleanup;
    }

16904
    current = virDomainHasCurrentSnapshot(dom, 0);
16905 16906 16907 16908
    if (current < 0) {
        goto cleanup;
    } else if (!current) {
        vshError(ctl, _("domain '%s' has no current snapshot"), domname);
16909
        goto cleanup;
16910
    } else {
E
Eric Blake 已提交
16911
        const char *name = NULL;
16912 16913 16914 16915

        if (!(snapshot = virDomainSnapshotCurrent(dom, 0)))
            goto cleanup;

16916
        if (vshCommandOptBool(cmd, "name")) {
E
Eric Blake 已提交
16917
            name = virDomainSnapshotGetName(snapshot);
16918 16919
            if (!name)
                goto cleanup;
E
Eric Blake 已提交
16920 16921 16922 16923
        } else {
            xml = virDomainSnapshotGetXMLDesc(snapshot, flags);
            if (!xml)
                goto cleanup;
16924 16925 16926
        }

        vshPrint(ctl, "%s", name ? name : xml);
16927 16928
    }

E
Eric Blake 已提交
16929
    ret = true;
16930 16931

cleanup:
16932 16933
    if (!ret)
        virshReportError(ctl);
16934
    VIR_FREE(xml);
16935 16936 16937 16938 16939 16940 16941 16942
    if (snapshot)
        virDomainSnapshotFree(snapshot);
    if (dom)
        virDomainFree(dom);

    return ret;
}

16943
/* Helper function to get the name of a snapshot's parent.  Caller
16944 16945 16946 16947 16948 16949
 * must free the result.  Returns 0 on success (including when it was
 * proven no parent exists), and -1 on failure with error reported
 * (such as no snapshot support or domain deleted in meantime).  */
static int
vshGetSnapshotParent(vshControl *ctl, virDomainSnapshotPtr snapshot,
                     char **parent_name)
16950 16951 16952 16953 16954
{
    virDomainSnapshotPtr parent = NULL;
    char *xml = NULL;
    xmlDocPtr xmldoc = NULL;
    xmlXPathContextPtr ctxt = NULL;
16955 16956 16957
    int ret = -1;

    *parent_name = NULL;
16958 16959

    /* Try new API, since it is faster. */
16960
    if (!ctl->useSnapshotOld) {
16961 16962 16963
        parent = virDomainSnapshotGetParent(snapshot, 0);
        if (parent) {
            /* API works, and virDomainSnapshotGetName will succeed */
16964 16965
            *parent_name = vshStrdup(ctl, virDomainSnapshotGetName(parent));
            ret = 0;
16966 16967 16968 16969
            goto cleanup;
        }
        if (last_error->code == VIR_ERR_NO_DOMAIN_SNAPSHOT) {
            /* API works, and we found a root with no parent */
16970
            ret = 0;
16971 16972 16973
            goto cleanup;
        }
        /* API didn't work, fall back to XML scraping. */
16974
        ctl->useSnapshotOld = true;
16975 16976 16977 16978 16979 16980 16981 16982 16983 16984
    }

    xml = virDomainSnapshotGetXMLDesc(snapshot, 0);
    if (!xml)
        goto cleanup;

    xmldoc = virXMLParseStringCtxt(xml, _("(domain_snapshot)"), &ctxt);
    if (!xmldoc)
        goto cleanup;

16985 16986
    *parent_name = virXPathString("string(/domainsnapshot/parent/name)", ctxt);
    ret = 0;
16987 16988

cleanup:
16989 16990 16991 16992 16993 16994 16995
    if (ret < 0) {
        virshReportError(ctl);
        vshError(ctl, "%s", _("unable to determine if snapshot has parent"));
    } else {
        virFreeError(last_error);
        last_error = NULL;
    }
16996 16997 16998 16999 17000
    if (parent)
        virDomainSnapshotFree(parent);
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xmldoc);
    VIR_FREE(xml);
17001
    return ret;
17002 17003
}

E
Eric Blake 已提交
17004 17005 17006 17007 17008 17009 17010 17011 17012 17013 17014 17015 17016 17017 17018 17019 17020 17021 17022 17023 17024 17025 17026 17027 17028 17029 17030 17031 17032 17033 17034 17035 17036 17037 17038 17039 17040 17041 17042 17043 17044 17045 17046 17047 17048 17049 17050 17051 17052 17053 17054 17055 17056 17057 17058 17059 17060 17061 17062 17063 17064 17065 17066 17067 17068 17069 17070 17071 17072 17073 17074 17075 17076 17077 17078 17079 17080 17081 17082 17083 17084 17085 17086 17087 17088 17089 17090 17091 17092 17093 17094 17095 17096 17097 17098 17099 17100 17101 17102 17103 17104 17105 17106 17107 17108 17109 17110 17111 17112 17113 17114 17115 17116 17117 17118 17119 17120 17121 17122 17123 17124 17125 17126
/*
 * "snapshot-info" command
 */
static const vshCmdInfo info_snapshot_info[] = {
    {"help", N_("snapshot information")},
    {"desc", N_("Returns basic information about a snapshot.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_snapshot_info[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"snapshotname", VSH_OT_DATA, 0, N_("snapshot name")},
    {"current", VSH_OT_BOOL, 0, N_("info on current snapshot")},
    {NULL, 0, 0, NULL}
};

static bool
cmdSnapshotInfo(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    virDomainSnapshotPtr snapshot = NULL;
    const char *name;
    char *doc = NULL;
    char *tmp;
    char *parent = NULL;
    bool ret = false;
    int count;
    unsigned int flags;
    int current;
    int metadata;

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

    dom = vshCommandOptDomain(ctl, cmd, NULL);
    if (dom == NULL)
        return false;

    if (vshLookupSnapshot(ctl, cmd, "snapshotname", true, dom,
                          &snapshot, &name) < 0)
        goto cleanup;

    vshPrint(ctl, "%-15s %s\n", _("Name:"), name);
    vshPrint(ctl, "%-15s %s\n", _("Domain:"), virDomainGetName(dom));

    /* Determine if snapshot is current; this is useful enough that we
     * attempt a fallback.  */
    current = virDomainSnapshotIsCurrent(snapshot, 0);
    if (current < 0) {
        virDomainSnapshotPtr other = virDomainSnapshotCurrent(dom, 0);

        virResetLastError();
        current = 0;
        if (other) {
            if (STREQ(name, virDomainSnapshotGetName(other)))
                current = 1;
            virDomainSnapshotFree(other);
        }
    }
    vshPrint(ctl, "%-15s %s\n", _("Current:"),
             current > 0 ? _("yes") : _("no"));

    /* Get the XML configuration of the snapshot to determine the
     * state of the machine at the time of the snapshot.  */
    doc = virDomainSnapshotGetXMLDesc(snapshot, 0);
    if (!doc)
        goto cleanup;

    tmp = strstr(doc, "<state>");
    if (!tmp) {
        vshError(ctl, "%s",
                 _("unexpected problem reading snapshot xml"));
        goto cleanup;
    }
    tmp += strlen("<state>");
    vshPrint(ctl, "%-15s %.*s\n", _("State:"),
             (int) (strchr(tmp, '<') - tmp), tmp);

    if (vshGetSnapshotParent(ctl, snapshot, &parent) < 0)
        goto cleanup;
    vshPrint(ctl, "%-15s %s\n", _("Parent:"), parent ? parent : "-");

    /* Children, Descendants.  After this point, the fallback to
     * compute children is too expensive, so we gracefully quit if the
     * APIs don't exist.  */
    if (ctl->useSnapshotOld) {
        ret = true;
        goto cleanup;
    }
    flags = 0;
    count = virDomainSnapshotNumChildren(snapshot, flags);
    if (count < 0)
        goto cleanup;
    vshPrint(ctl, "%-15s %d\n", _("Children:"), count);
    flags = VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS;
    count = virDomainSnapshotNumChildren(snapshot, flags);
    if (count < 0)
        goto cleanup;
    vshPrint(ctl, "%-15s %d\n", _("Descendants:"), count);

    /* Metadata; the fallback here relies on the fact that metadata
     * used to have an all-or-nothing effect on snapshot count.  */
    metadata = virDomainSnapshotHasMetadata(snapshot, 0);
    if (metadata < 0) {
        metadata = virDomainSnapshotNum(dom,
                                        VIR_DOMAIN_SNAPSHOT_LIST_METADATA);
        virResetLastError();
    }
    if (metadata >= 0)
        vshPrint(ctl, "%-15s %s\n", _("Metadata:"),
                 metadata ? _("yes") : _("no"));

    ret = true;

cleanup:
    VIR_FREE(doc);
    VIR_FREE(parent);
    if (snapshot)
        virDomainSnapshotFree(snapshot);
    virDomainFree(dom);
    return ret;
}

17127 17128 17129 17130 17131 17132 17133 17134 17135 17136 17137 17138 17139 17140 17141 17142 17143 17144 17145 17146 17147 17148 17149 17150 17151 17152 17153 17154 17155 17156 17157 17158 17159 17160 17161 17162 17163 17164 17165 17166 17167 17168 17169 17170 17171 17172 17173 17174 17175
/* Helpers for collecting a list of snapshots.  */
struct vshSnap {
    virDomainSnapshotPtr snap;
    char *parent;
};
struct vshSnapshotList {
    struct vshSnap *snaps;
    int nsnaps;
};
typedef struct vshSnapshotList *vshSnapshotListPtr;

static void
vshSnapshotListFree(vshSnapshotListPtr snaplist)
{
    int i;

    if (!snaplist)
        return;
    if (snaplist->snaps) {
        for (i = 0; i < snaplist->nsnaps; i++) {
            if (snaplist->snaps[i].snap)
                virDomainSnapshotFree(snaplist->snaps[i].snap);
            VIR_FREE(snaplist->snaps[i].parent);
        }
        VIR_FREE(snaplist->snaps);
    }
    VIR_FREE(snaplist);
}

static int
vshSnapSorter(const void *a, const void *b)
{
    const struct vshSnap *sa = a;
    const struct vshSnap *sb = b;

    if (sa->snap && !sb->snap)
        return -1;
    if (!sa->snap)
        return sb->snap != NULL;

    /* User visible sort, so we want locale-specific case comparison.  */
    return strcasecmp(virDomainSnapshotGetName(sa->snap),
                      virDomainSnapshotGetName(sb->snap));
}

/* Compute a list of snapshots from DOM.  If FROM is provided, the
 * list is limited to descendants of the given snapshot.  If FLAGS is
 * given, the list is filtered.  If TREE is specified, then all but
 * FROM or the roots will also have parent information.  */
17176
static vshSnapshotListPtr
17177 17178 17179 17180 17181 17182 17183 17184 17185
vshSnapshotListCollect(vshControl *ctl, virDomainPtr dom,
                       virDomainSnapshotPtr from,
                       unsigned int flags, bool tree)
{
    int i;
    char **names = NULL;
    int count = -1;
    bool descendants = false;
    bool roots = false;
17186
    virDomainSnapshotPtr *snaps;
17187 17188 17189 17190 17191 17192
    vshSnapshotListPtr snaplist = vshMalloc(ctl, sizeof(*snaplist));
    vshSnapshotListPtr ret = NULL;
    const char *fromname = NULL;
    int start_index = -1;
    int deleted = 0;

17193 17194 17195 17196 17197 17198 17199 17200 17201 17202 17203 17204 17205 17206 17207 17208 17209 17210 17211 17212 17213 17214 17215 17216 17217 17218 17219 17220 17221
    /* Try the interface available in 0.9.13 and newer.  */
    if (!ctl->useSnapshotOld) {
        if (from)
            count = virDomainSnapshotListAllChildren(from, &snaps, flags);
        else
            count = virDomainListAllSnapshots(dom, &snaps, flags);
    }
    if (count >= 0) {
        /* When mixing --from and --tree, we also want a copy of from
         * in the list, but with no parent for that one entry.  */
        snaplist->snaps = vshCalloc(ctl, sizeof(*snaplist->snaps),
                                    count + (tree && from));
        snaplist->nsnaps = count;
        for (i = 0; i < count; i++)
            snaplist->snaps[i].snap = snaps[i];
        VIR_FREE(snaps);
        if (tree) {
            for (i = 0; i < count; i++) {
                if (vshGetSnapshotParent(ctl, snaplist->snaps[i].snap,
                                         &snaplist->snaps[i].parent) < 0)
                    goto cleanup;
            }
            if (from) {
                snaps[snaplist->nsnaps++] = from;
                virDomainSnapshotRef(from);
            }
        }
        goto success;
    }
17222

E
Eric Blake 已提交
17223 17224 17225 17226 17227 17228 17229 17230 17231 17232 17233 17234 17235 17236 17237 17238 17239 17240 17241 17242 17243 17244 17245 17246
    /* Assume that if we got this far, then the --no-leaves and
     * --no-metadata flags were not supported.  Disable groups that
     * have no impact.  */
    /* XXX should we emulate --no-leaves?  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_NO_LEAVES &&
        flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES)
        flags &= ~(VIR_DOMAIN_SNAPSHOT_LIST_NO_LEAVES |
                   VIR_DOMAIN_SNAPSHOT_LIST_LEAVES);
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA &&
        flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)
        flags &= ~(VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA |
                   VIR_DOMAIN_SNAPSHOT_LIST_METADATA);
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA) {
        /* We can emulate --no-metadata if --metadata was supported,
         * since it was an all-or-none attribute on old servers.  */
        count = virDomainSnapshotNum(dom,
                                     VIR_DOMAIN_SNAPSHOT_LIST_METADATA);
        if (count < 0)
            goto cleanup;
        if (count > 0)
            return snaplist;
        flags &= ~VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA;
    }

17247 17248 17249 17250 17251 17252 17253 17254 17255 17256 17257 17258 17259 17260 17261 17262 17263 17264 17265 17266 17267 17268 17269 17270 17271 17272 17273 17274 17275 17276 17277 17278 17279 17280 17281 17282 17283 17284 17285 17286 17287 17288 17289 17290 17291 17292 17293 17294 17295 17296 17297 17298 17299 17300 17301 17302 17303 17304 17305 17306 17307 17308 17309 17310 17311 17312 17313 17314 17315 17316 17317 17318 17319 17320 17321 17322 17323 17324 17325 17326 17327 17328 17329 17330 17331 17332 17333 17334 17335 17336 17337 17338 17339 17340 17341 17342 17343 17344 17345 17346 17347 17348 17349 17350 17351 17352 17353 17354 17355 17356 17357 17358 17359 17360 17361 17362 17363 17364 17365 17366 17367 17368 17369 17370 17371 17372 17373 17374 17375 17376 17377 17378 17379 17380 17381 17382 17383 17384 17385 17386 17387 17388 17389 17390 17391 17392 17393 17394 17395 17396 17397 17398 17399 17400 17401 17402 17403 17404 17405 17406 17407 17408 17409 17410 17411 17412 17413 17414 17415 17416 17417 17418 17419 17420 17421 17422 17423 17424 17425 17426 17427 17428 17429 17430 17431 17432 17433 17434 17435 17436 17437 17438 17439 17440 17441 17442 17443 17444 17445 17446 17447 17448 17449 17450 17451 17452 17453 17454 17455 17456 17457
    /* This uses the interfaces available in 0.8.0-0.9.6
     * (virDomainSnapshotListNames, global list only) and in
     * 0.9.7-0.9.12 (addition of virDomainSnapshotListChildrenNames
     * for child listing, and new flags), as follows, with [*] by the
     * combinations that need parent info (either for filtering
     * purposes or for the resulting tree listing):
     *                              old               new
     * list                         global as-is      global as-is
     * list --roots                *global + filter   global + flags
     * list --from                 *global + filter   child as-is
     * list --from --descendants   *global + filter   child + flags
     * list --tree                 *global as-is     *global as-is
     * list --tree --from          *global + filter  *child + flags
     *
     * Additionally, when --tree and --from are both used, from is
     * added to the final list as the only element without a parent.
     * Otherwise, --from does not appear in the final list.
     */
    if (from) {
        fromname = virDomainSnapshotGetName(from);
        if (!fromname) {
            vshError(ctl, "%s", _("Could not get snapshot name"));
            goto cleanup;
        }
        descendants = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) || tree;
        if (tree)
            flags |= VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS;

        /* Determine if we can use the new child listing API.  */
        if (ctl->useSnapshotOld ||
            ((count = virDomainSnapshotNumChildren(from, flags)) < 0 &&
             last_error->code == VIR_ERR_NO_SUPPORT)) {
            /* We can emulate --from.  */
            /* XXX can we also emulate --leaves? */
            virFreeError(last_error);
            last_error = NULL;
            ctl->useSnapshotOld = true;
            flags &= ~VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS;
            goto global;
        }
        if (tree && count >= 0)
            count++;
    } else {
    global:
        /* Global listing (including fallback when --from failed with
         * child listing).  */
        count = virDomainSnapshotNum(dom, flags);

        /* Fall back to simulation if --roots was unsupported. */
        /* XXX can we also emulate --leaves? */
        if (!from && count < 0 && last_error->code == VIR_ERR_INVALID_ARG &&
            (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS)) {
            virFreeError(last_error);
            last_error = NULL;
            roots = true;
            flags &= ~VIR_DOMAIN_SNAPSHOT_LIST_ROOTS;
            count = virDomainSnapshotNum(dom, flags);
        }
    }

    if (count < 0) {
        if (!last_error)
            vshError(ctl, _("failed to collect snapshot list"));
        goto cleanup;
    }

    if (!count)
        goto success;

    names = vshCalloc(ctl, sizeof(*names), count);

    /* Now that we have a count, collect the list.  */
    if (from && !ctl->useSnapshotOld) {
        if (tree) {
            if (count)
                count = virDomainSnapshotListChildrenNames(from, names + 1,
                                                           count - 1, flags);
            if (count >= 0) {
                count++;
                names[0] = vshStrdup(ctl, fromname);
            }
        } else {
            count = virDomainSnapshotListChildrenNames(from, names,
                                                       count, flags);
        }
    } else {
        count = virDomainSnapshotListNames(dom, names, count, flags);
    }
    if (count < 0)
        goto cleanup;

    snaplist->snaps = vshCalloc(ctl, sizeof(*snaplist->snaps), count);
    snaplist->nsnaps = count;
    for (i = 0; i < count; i++) {
        snaplist->snaps[i].snap = virDomainSnapshotLookupByName(dom,
                                                                names[i], 0);
        if (!snaplist->snaps[i].snap)
            goto cleanup;
    }

    /* Collect parents when needed.  With the new API, --tree and
     * --from together put from as the first element without a parent;
     * with the old API we still need to do a post-process filtering
     * based on all parent information.  */
    if (tree || (from && ctl->useSnapshotOld) || roots) {
        for (i = (from && !ctl->useSnapshotOld); i < count; i++) {
            if (from && ctl->useSnapshotOld && STREQ(names[i], fromname)) {
                start_index = i;
                if (tree)
                    continue;
            }
            if (vshGetSnapshotParent(ctl, snaplist->snaps[i].snap,
                                     &snaplist->snaps[i].parent) < 0)
                goto cleanup;
            if ((from && ((tree && !snaplist->snaps[i].parent) ||
                          (!descendants &&
                           STRNEQ_NULLABLE(fromname,
                                           snaplist->snaps[i].parent)))) ||
                (roots && snaplist->snaps[i].parent)) {
                virDomainSnapshotFree(snaplist->snaps[i].snap);
                snaplist->snaps[i].snap = NULL;
                VIR_FREE(snaplist->snaps[i].parent);
                deleted++;
            }
        }
    }
    if (tree)
        goto success;

    if (ctl->useSnapshotOld && descendants) {
        bool changed = false;
        bool remaining = false;

        /* Make multiple passes over the list - first pass finds
         * direct children and NULLs out all roots and from, remaining
         * passes NULL out any undecided entry whose parent is not
         * still in list.  We mark known descendants by clearing
         * snaps[i].parents.  Sorry, this is O(n^3) - hope your
         * hierarchy isn't huge.  XXX Is it worth making O(n^2 log n)
         * by using qsort and bsearch?  */
        if (start_index < 0) {
            vshError(ctl, _("snapshot %s disappeared from list"), fromname);
            goto cleanup;
        }
        for (i = 0; i < count; i++) {
            if (i == start_index || !snaplist->snaps[i].parent) {
                VIR_FREE(names[i]);
                virDomainSnapshotFree(snaplist->snaps[i].snap);
                snaplist->snaps[i].snap = NULL;
                VIR_FREE(snaplist->snaps[i].parent);
                deleted++;
            } else if (STREQ(snaplist->snaps[i].parent, fromname)) {
                VIR_FREE(snaplist->snaps[i].parent);
                changed = true;
            } else {
                remaining = true;
            }
        }
        if (!changed) {
            ret = vshMalloc(ctl, sizeof(*snaplist));
            goto cleanup;
        }
        while (changed && remaining) {
            changed = remaining = false;
            for (i = 0; i < count; i++) {
                bool found_parent = false;
                int j;

                if (!names[i] || !snaplist->snaps[i].parent)
                    continue;
                for (j = 0; j < count; j++) {
                    if (!names[j] || i == j)
                        continue;
                    if (STREQ(snaplist->snaps[i].parent, names[j])) {
                        found_parent = true;
                        if (!snaplist->snaps[j].parent)
                            VIR_FREE(snaplist->snaps[i].parent);
                        else
                            remaining = true;
                        break;
                    }
                }
                if (!found_parent) {
                    changed = true;
                    VIR_FREE(names[i]);
                    virDomainSnapshotFree(snaplist->snaps[i].snap);
                    snaplist->snaps[i].snap = NULL;
                    VIR_FREE(snaplist->snaps[i].parent);
                    deleted++;
                }
            }
        }
    }

success:
    qsort(snaplist->snaps, snaplist->nsnaps, sizeof(*snaplist->snaps),
          vshSnapSorter);
    snaplist->nsnaps -= deleted;

    ret = snaplist;
    snaplist = NULL;

cleanup:
    vshSnapshotListFree(snaplist);
    if (names)
        for (i = 0; i < count; i++)
            VIR_FREE(names[i]);
    VIR_FREE(names);
    return ret;
}

17458 17459 17460 17461 17462 17463 17464 17465 17466
static const char *
vshSnapshotListLookup(int id, bool parent, void *opaque)
{
    vshSnapshotListPtr snaplist = opaque;
    if (parent)
        return snaplist->snaps[id].parent;
    return virDomainSnapshotGetName(snaplist->snaps[id].snap);
}

17467 17468 17469 17470 17471 17472 17473 17474 17475 17476 17477
/*
 * "snapshot-list" command
 */
static const vshCmdInfo info_snapshot_list[] = {
    {"help", N_("List snapshots for a domain")},
    {"desc", N_("Snapshot List")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_snapshot_list[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
17478
    {"parent", VSH_OT_BOOL, 0, N_("add a column showing parent snapshot")},
17479
    {"roots", VSH_OT_BOOL, 0, N_("list only snapshots without parents")},
17480
    {"leaves", VSH_OT_BOOL, 0, N_("list only snapshots without children")},
E
Eric Blake 已提交
17481 17482
    {"no-leaves", VSH_OT_BOOL, 0,
     N_("list only snapshots that are not leaves (with children)")},
17483 17484
    {"metadata", VSH_OT_BOOL, 0,
     N_("list only snapshots that have metadata that would prevent undefine")},
E
Eric Blake 已提交
17485 17486
    {"no-metadata", VSH_OT_BOOL, 0,
     N_("list only snapshots that have no metadata managed by libvirt")},
17487
    {"tree", VSH_OT_BOOL, 0, N_("list snapshots in a tree")},
17488
    {"from", VSH_OT_DATA, 0, N_("limit list to children of given snapshot")},
17489 17490
    {"current", VSH_OT_BOOL, 0,
     N_("limit list to children of current snapshot")},
17491
    {"descendants", VSH_OT_BOOL, 0, N_("with --from, list all descendants")},
17492 17493 17494
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
17495
static bool
17496 17497 17498
cmdSnapshotList(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
E
Eric Blake 已提交
17499
    bool ret = false;
17500
    unsigned int flags = 0;
17501
    bool show_parent = false;
17502 17503 17504 17505 17506 17507
    int i;
    xmlDocPtr xml = NULL;
    xmlXPathContextPtr ctxt = NULL;
    char *doc = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    char *state = NULL;
17508
    char *parent = NULL;
17509 17510
    long long creation_longlong;
    time_t creation_time_t;
17511 17512
    char timestr[100];
    struct tm time_info;
17513
    bool tree = vshCommandOptBool(cmd, "tree");
17514
    bool leaves = vshCommandOptBool(cmd, "leaves");
E
Eric Blake 已提交
17515
    bool no_leaves = vshCommandOptBool(cmd, "no-leaves");
17516 17517
    const char *from = NULL;
    virDomainSnapshotPtr start = NULL;
17518
    vshSnapshotListPtr snaplist = NULL;
17519

17520 17521 17522 17523 17524 17525 17526 17527 17528 17529
    if (!vshConnectionUsability(ctl, ctl->conn))
        goto cleanup;

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

    if ((vshCommandOptBool(cmd, "from") ||
         vshCommandOptBool(cmd, "current")) &&
        vshLookupSnapshot(ctl, cmd, "from", true, dom, &start, &from) < 0)
17530
        goto cleanup;
17531

17532
    if (vshCommandOptBool(cmd, "parent")) {
17533 17534
        if (vshCommandOptBool(cmd, "roots")) {
            vshError(ctl, "%s",
17535
                     _("--parent and --roots are mutually exclusive"));
17536
            goto cleanup;
17537
        }
17538 17539
        if (tree) {
            vshError(ctl, "%s",
17540
                     _("--parent and --tree are mutually exclusive"));
17541
            goto cleanup;
17542
        }
17543
        show_parent = true;
17544
    } else if (vshCommandOptBool(cmd, "roots")) {
17545 17546
        if (tree) {
            vshError(ctl, "%s",
17547
                     _("--roots and --tree are mutually exclusive"));
17548
            goto cleanup;
17549
        }
17550 17551 17552
        if (from) {
            vshError(ctl, "%s",
                     _("--roots and --from are mutually exclusive"));
17553
            goto cleanup;
17554
        }
17555 17556
        flags |= VIR_DOMAIN_SNAPSHOT_LIST_ROOTS;
    }
17557 17558 17559 17560
    if (leaves) {
        if (tree) {
            vshError(ctl, "%s",
                     _("--leaves and --tree are mutually exclusive"));
17561
            goto cleanup;
17562 17563 17564
        }
        flags |= VIR_DOMAIN_SNAPSHOT_LIST_LEAVES;
    }
E
Eric Blake 已提交
17565 17566 17567 17568 17569 17570 17571 17572
    if (no_leaves) {
        if (tree) {
            vshError(ctl, "%s",
                     _("--no-leaves and --tree are mutually exclusive"));
            goto cleanup;
        }
        flags |= VIR_DOMAIN_SNAPSHOT_LIST_NO_LEAVES;
    }
17573 17574 17575

    if (vshCommandOptBool(cmd, "metadata")) {
        flags |= VIR_DOMAIN_SNAPSHOT_LIST_METADATA;
17576
    }
E
Eric Blake 已提交
17577 17578 17579
    if (vshCommandOptBool(cmd, "no-metadata")) {
        flags |= VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA;
    }
17580

17581 17582 17583 17584 17585
    if (vshCommandOptBool(cmd, "descendants")) {
        if (!from) {
            vshError(ctl, "%s",
                     _("--descendants requires either --from or --current"));
            goto cleanup;
17586
        }
17587
        flags |= VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS;
17588 17589
    }

17590 17591
    if ((snaplist = vshSnapshotListCollect(ctl, dom, start, flags,
                                           tree)) == NULL)
17592 17593
        goto cleanup;

17594
    if (!tree) {
17595
        if (show_parent)
17596 17597 17598 17599 17600 17601
            vshPrintExtra(ctl, " %-20s %-25s %-15s %s",
                          _("Name"), _("Creation Time"), _("State"),
                          _("Parent"));
        else
            vshPrintExtra(ctl, " %-20s %-25s %s",
                          _("Name"), _("Creation Time"), _("State"));
E
Eric Blake 已提交
17602 17603
        vshPrintExtra(ctl, "\n"
"------------------------------------------------------------\n");
17604
    }
17605

17606
    if (!snaplist->nsnaps) {
17607 17608 17609
        ret = true;
        goto cleanup;
    }
17610

17611
    if (tree) {
17612 17613 17614 17615
        for (i = 0; i < snaplist->nsnaps; i++) {
            if (!snaplist->snaps[i].parent &&
                vshTreePrint(ctl, vshSnapshotListLookup, snaplist,
                             snaplist->nsnaps, i) < 0)
17616
                goto cleanup;
17617 17618 17619
        }
        ret = true;
        goto cleanup;
E
Eric Blake 已提交
17620 17621
    }

17622 17623
    for (i = 0; i < snaplist->nsnaps; i++) {
        const char *name;
17624

E
Eric Blake 已提交
17625 17626 17627 17628 17629 17630
        /* free up memory from previous iterations of the loop */
        VIR_FREE(parent);
        VIR_FREE(state);
        xmlXPathFreeContext(ctxt);
        xmlFreeDoc(xml);
        VIR_FREE(doc);
17631

17632 17633 17634
        snapshot = snaplist->snaps[i].snap;
        name = virDomainSnapshotGetName(snapshot);
        assert(name);
17635

E
Eric Blake 已提交
17636 17637 17638
        doc = virDomainSnapshotGetXMLDesc(snapshot, 0);
        if (!doc)
            continue;
17639

E
Eric Blake 已提交
17640 17641 17642
        xml = virXMLParseStringCtxt(doc, _("(domain_snapshot)"), &ctxt);
        if (!xml)
            continue;
17643

17644
        if (show_parent)
E
Eric Blake 已提交
17645 17646
            parent = virXPathString("string(/domainsnapshot/parent/name)",
                                    ctxt);
17647

E
Eric Blake 已提交
17648 17649 17650 17651 17652 17653 17654 17655 17656 17657
        state = virXPathString("string(/domainsnapshot/state)", ctxt);
        if (state == NULL)
            continue;
        if (virXPathLongLong("string(/domainsnapshot/creationTime)", ctxt,
                             &creation_longlong) < 0)
            continue;
        creation_time_t = creation_longlong;
        if (creation_time_t != creation_longlong) {
            vshError(ctl, "%s", _("time_t overflow"));
            continue;
17658
        }
E
Eric Blake 已提交
17659 17660 17661 17662 17663 17664
        localtime_r(&creation_time_t, &time_info);
        strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S %z",
                 &time_info);

        if (parent)
            vshPrint(ctl, " %-20s %-25s %-15s %s\n",
17665
                     name, timestr, state, parent);
E
Eric Blake 已提交
17666
        else
17667
            vshPrint(ctl, " %-20s %-25s %s\n", name, timestr, state);
17668 17669
    }

E
Eric Blake 已提交
17670
    ret = true;
17671 17672 17673

cleanup:
    /* this frees up memory from the last iteration of the loop */
17674
    vshSnapshotListFree(snaplist);
17675
    VIR_FREE(parent);
17676
    VIR_FREE(state);
17677 17678
    if (start)
        virDomainSnapshotFree(start);
17679
    xmlXPathFreeContext(ctxt);
17680
    xmlFreeDoc(xml);
17681 17682 17683 17684 17685 17686 17687 17688 17689 17690 17691 17692 17693 17694 17695 17696 17697 17698 17699
    VIR_FREE(doc);
    if (dom)
        virDomainFree(dom);

    return ret;
}

/*
 * "snapshot-dumpxml" command
 */
static const vshCmdInfo info_snapshot_dumpxml[] = {
    {"help", N_("Dump XML for a domain snapshot")},
    {"desc", N_("Snapshot Dump XML")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_snapshot_dumpxml[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
    {"snapshotname", VSH_OT_DATA, VSH_OFLAG_REQ, N_("snapshot name")},
17700 17701
    {"security-info", VSH_OT_BOOL, 0,
     N_("include security sensitive information in XML dump")},
17702 17703 17704
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
17705
static bool
17706 17707 17708
cmdSnapshotDumpXML(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
E
Eric Blake 已提交
17709
    bool ret = false;
17710
    const char *name = NULL;
17711 17712
    virDomainSnapshotPtr snapshot = NULL;
    char *xml = NULL;
17713 17714 17715 17716
    unsigned int flags = 0;

    if (vshCommandOptBool(cmd, "security-info"))
        flags |= VIR_DOMAIN_XML_SECURE;
17717

17718
    if (!vshConnectionUsability(ctl, ctl->conn))
17719 17720 17721 17722 17723 17724
        goto cleanup;

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

17725
    if (vshCommandOptString(cmd, "snapshotname", &name) <= 0)
17726 17727 17728 17729 17730 17731
        goto cleanup;

    snapshot = virDomainSnapshotLookupByName(dom, name, 0);
    if (snapshot == NULL)
        goto cleanup;

17732
    xml = virDomainSnapshotGetXMLDesc(snapshot, flags);
17733 17734 17735
    if (!xml)
        goto cleanup;

17736
    vshPrint(ctl, "%s", xml);
17737

E
Eric Blake 已提交
17738
    ret = true;
17739 17740 17741 17742 17743 17744 17745 17746 17747 17748 17749

cleanup:
    VIR_FREE(xml);
    if (snapshot)
        virDomainSnapshotFree(snapshot);
    if (dom)
        virDomainFree(dom);

    return ret;
}

E
Eric Blake 已提交
17750 17751 17752 17753
/*
 * "snapshot-parent" command
 */
static const vshCmdInfo info_snapshot_parent[] = {
E
Eric Blake 已提交
17754
    {"help", N_("Get the name of the parent of a snapshot")},
E
Eric Blake 已提交
17755 17756 17757 17758 17759 17760
    {"desc", N_("Extract the snapshot's parent, if any")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_snapshot_parent[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
17761 17762
    {"snapshotname", VSH_OT_DATA, 0, N_("find parent of snapshot name")},
    {"current", VSH_OT_BOOL, 0, N_("find parent of current snapshot")},
E
Eric Blake 已提交
17763 17764 17765 17766 17767 17768 17769 17770 17771 17772 17773 17774 17775 17776 17777 17778 17779 17780 17781
    {NULL, 0, 0, NULL}
};

static bool
cmdSnapshotParent(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
    bool ret = false;
    const char *name = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    char *parent = NULL;

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

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

17782 17783
    if (vshLookupSnapshot(ctl, cmd, "snapshotname", true, dom,
                          &snapshot, &name) < 0)
E
Eric Blake 已提交
17784 17785
        goto cleanup;

17786
    if (vshGetSnapshotParent(ctl, snapshot, &parent) < 0)
E
Eric Blake 已提交
17787
        goto cleanup;
17788 17789 17790 17791
    if (!parent) {
        vshError(ctl, _("snapshot '%s' has no parent"), name);
        goto cleanup;
    }
E
Eric Blake 已提交
17792 17793 17794 17795 17796 17797 17798 17799 17800 17801 17802 17803 17804 17805 17806

    vshPrint(ctl, "%s", parent);

    ret = true;

cleanup:
    VIR_FREE(parent);
    if (snapshot)
        virDomainSnapshotFree(snapshot);
    if (dom)
        virDomainFree(dom);

    return ret;
}

17807
/*
17808
 * "snapshot-revert" command
17809
 */
17810
static const vshCmdInfo info_snapshot_revert[] = {
17811 17812 17813 17814 17815
    {"help", N_("Revert a domain to a snapshot")},
    {"desc", N_("Revert domain to snapshot")},
    {NULL, NULL}
};

17816
static const vshCmdOptDef opts_snapshot_revert[] = {
17817
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
17818 17819
    {"snapshotname", VSH_OT_DATA, 0, N_("snapshot name")},
    {"current", VSH_OT_BOOL, 0, N_("revert to current snapshot")},
17820 17821
    {"running", VSH_OT_BOOL, 0, N_("after reverting, change state to running")},
    {"paused", VSH_OT_BOOL, 0, N_("after reverting, change state to paused")},
E
Eric Blake 已提交
17822
    {"force", VSH_OT_BOOL, 0, N_("try harder on risky reverts")},
17823 17824 17825
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
17826
static bool
17827
cmdDomainSnapshotRevert(vshControl *ctl, const vshCmd *cmd)
17828 17829
{
    virDomainPtr dom = NULL;
E
Eric Blake 已提交
17830
    bool ret = false;
17831
    const char *name = NULL;
17832
    virDomainSnapshotPtr snapshot = NULL;
17833
    unsigned int flags = 0;
E
Eric Blake 已提交
17834 17835
    bool force = false;
    int result;
17836 17837 17838 17839 17840

    if (vshCommandOptBool(cmd, "running"))
        flags |= VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING;
    if (vshCommandOptBool(cmd, "paused"))
        flags |= VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED;
E
Eric Blake 已提交
17841 17842 17843 17844 17845 17846
    /* We want virsh snapshot-revert --force to work even when talking
     * to older servers that did the unsafe revert by default but
     * reject the flag, so we probe without the flag, and only use it
     * when the error says it will make a difference.  */
    if (vshCommandOptBool(cmd, "force"))
        force = true;
17847

17848
    if (!vshConnectionUsability(ctl, ctl->conn))
17849 17850 17851 17852 17853 17854
        goto cleanup;

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

17855 17856
    if (vshLookupSnapshot(ctl, cmd, "snapshotname", true, dom,
                          &snapshot, &name) < 0)
17857 17858
        goto cleanup;

E
Eric Blake 已提交
17859 17860 17861 17862 17863 17864 17865 17866 17867
    result = virDomainRevertToSnapshot(snapshot, flags);
    if (result < 0 && force &&
        last_error->code == VIR_ERR_SNAPSHOT_REVERT_RISKY) {
        flags |= VIR_DOMAIN_SNAPSHOT_REVERT_FORCE;
        virFreeError(last_error);
        last_error = NULL;
        result = virDomainRevertToSnapshot(snapshot, flags);
    }
    if (result < 0)
17868 17869
        goto cleanup;

E
Eric Blake 已提交
17870
    ret = true;
17871 17872 17873 17874 17875 17876 17877 17878 17879 17880 17881 17882 17883 17884 17885 17886 17887 17888 17889 17890 17891

cleanup:
    if (snapshot)
        virDomainSnapshotFree(snapshot);
    if (dom)
        virDomainFree(dom);

    return ret;
}

/*
 * "snapshot-delete" command
 */
static const vshCmdInfo info_snapshot_delete[] = {
    {"help", N_("Delete a domain snapshot")},
    {"desc", N_("Snapshot Delete")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_snapshot_delete[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
17892 17893
    {"snapshotname", VSH_OT_DATA, 0, N_("snapshot name")},
    {"current", VSH_OT_BOOL, 0, N_("delete current snapshot")},
17894
    {"children", VSH_OT_BOOL, 0, N_("delete snapshot and all children")},
17895 17896 17897
    {"children-only", VSH_OT_BOOL, 0, N_("delete children but not snapshot")},
    {"metadata", VSH_OT_BOOL, 0,
     N_("delete only libvirt metadata, leaving snapshot contents behind")},
17898 17899 17900
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
17901
static bool
17902 17903 17904
cmdSnapshotDelete(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
E
Eric Blake 已提交
17905
    bool ret = false;
17906
    const char *name = NULL;
17907 17908 17909
    virDomainSnapshotPtr snapshot = NULL;
    unsigned int flags = 0;

17910
    if (!vshConnectionUsability(ctl, ctl->conn))
17911 17912 17913 17914 17915 17916
        goto cleanup;

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

17917 17918
    if (vshLookupSnapshot(ctl, cmd, "snapshotname", true, dom,
                          &snapshot, &name) < 0)
17919 17920 17921 17922
        goto cleanup;

    if (vshCommandOptBool(cmd, "children"))
        flags |= VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN;
17923 17924 17925 17926
    if (vshCommandOptBool(cmd, "children-only"))
        flags |= VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY;
    if (vshCommandOptBool(cmd, "metadata"))
        flags |= VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY;
17927

17928 17929 17930
    /* XXX If we wanted, we could emulate DELETE_CHILDREN_ONLY even on
     * older servers that reject the flag, by manually computing the
     * list of descendants.  But that's a lot of code to maintain.  */
17931
    if (virDomainSnapshotDelete(snapshot, flags) == 0) {
17932 17933 17934 17935
        if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY)
            vshPrint(ctl, _("Domain snapshot %s children deleted\n"), name);
        else
            vshPrint(ctl, _("Domain snapshot %s deleted\n"), name);
17936 17937
    } else {
        vshError(ctl, _("Failed to delete snapshot %s"), name);
17938
        goto cleanup;
17939
    }
17940

E
Eric Blake 已提交
17941
    ret = true;
17942 17943 17944 17945 17946 17947 17948 17949 17950 17951

cleanup:
    if (snapshot)
        virDomainSnapshotFree(snapshot);
    if (dom)
        virDomainFree(dom);

    return ret;
}

17952 17953 17954 17955 17956 17957 17958 17959 17960 17961 17962 17963 17964 17965 17966 17967 17968 17969 17970 17971 17972 17973 17974 17975 17976 17977 17978 17979 17980 17981 17982 17983 17984 17985 17986 17987 17988 17989 17990 17991 17992 17993 17994 17995 17996 17997 17998 17999 18000 18001 18002 18003 18004 18005 18006 18007 18008 18009 18010 18011 18012 18013 18014 18015 18016 18017 18018 18019 18020 18021 18022 18023 18024 18025 18026 18027 18028
/*
 * "domblkerror" command
 */
static const char *
vshDomainIOErrorToString(int error)
{
    switch ((virDomainDiskErrorCode) error) {
    case VIR_DOMAIN_DISK_ERROR_NONE:
        return _("no error");
    case VIR_DOMAIN_DISK_ERROR_UNSPEC:
        return _("unspecified error");
    case VIR_DOMAIN_DISK_ERROR_NO_SPACE:
        return _("no space");
    case VIR_DOMAIN_DISK_ERROR_LAST:
        ;
    }

    return _("unknown error");
}

static const vshCmdInfo info_domblkerror[] = {
    {"help", N_("Show errors on block devices")},
    {"desc", N_("Show block device errors")},
    {NULL, NULL}
};

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

static bool
cmdDomBlkError(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    virDomainDiskErrorPtr disks = NULL;
    unsigned int ndisks;
    int i;
    int count;
    bool ret = false;

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

    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
        return false;

    if ((count = virDomainGetDiskErrors(dom, NULL, 0, 0)) < 0)
        goto cleanup;
    ndisks = count;

    if (ndisks) {
        if (VIR_ALLOC_N(disks, ndisks) < 0)
            goto cleanup;

        if ((count = virDomainGetDiskErrors(dom, disks, ndisks, 0)) == -1)
            goto cleanup;
    }

    if (count == 0) {
        vshPrint(ctl, _("No errors found\n"));
    } else {
        for (i = 0; i < count; i++) {
            vshPrint(ctl, "%s: %s\n",
                     disks[i].disk,
                     vshDomainIOErrorToString(disks[i].error));
        }
    }

    ret = true;

cleanup:
    VIR_FREE(disks);
    virDomainFree(dom);
    return ret;
}

18029 18030 18031 18032
/*
 * "qemu-monitor-command" command
 */
static const vshCmdInfo info_qemu_monitor_command[] = {
18033 18034
    {"help", N_("QEMU Monitor Command")},
    {"desc", N_("QEMU Monitor Command")},
18035 18036 18037 18038 18039
    {NULL, NULL}
};

static const vshCmdOptDef opts_qemu_monitor_command[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
18040
    {"hmp", VSH_OT_BOOL, 0, N_("command is in human monitor protocol")},
18041
    {"cmd", VSH_OT_ARGV, VSH_OFLAG_REQ, N_("command")},
18042 18043 18044
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
18045
static bool
18046 18047 18048
cmdQemuMonitorCommand(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
E
Eric Blake 已提交
18049
    bool ret = false;
18050
    char *monitor_cmd = NULL;
18051
    char *result = NULL;
18052
    unsigned int flags = 0;
18053 18054 18055
    const vshCmdOpt *opt = NULL;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    bool pad = false;
18056 18057 18058 18059 18060 18061 18062 18063

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

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

18064 18065 18066 18067 18068 18069 18070 18071
    while ((opt = vshCommandOptArgv(cmd, opt))) {
        if (pad)
            virBufferAddChar(&buf, ' ');
        pad = true;
        virBufferAdd(&buf, opt->data, -1);
    }
    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to collect command"));
18072 18073
        goto cleanup;
    }
18074
    monitor_cmd = virBufferContentAndReset(&buf);
18075

18076 18077 18078 18079
    if (vshCommandOptBool(cmd, "hmp"))
        flags |= VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP;

    if (virDomainQemuMonitorCommand(dom, monitor_cmd, &result, flags) < 0)
18080 18081 18082 18083
        goto cleanup;

    printf("%s\n", result);

E
Eric Blake 已提交
18084
    ret = true;
18085 18086 18087

cleanup:
    VIR_FREE(result);
18088
    VIR_FREE(monitor_cmd);
18089 18090 18091 18092 18093 18094
    if (dom)
        virDomainFree(dom);

    return ret;
}

18095 18096 18097 18098 18099 18100 18101 18102 18103 18104 18105 18106 18107 18108 18109 18110 18111 18112 18113 18114
/*
 * "qemu-attach" command
 */
static const vshCmdInfo info_qemu_attach[] = {
    {"help", N_("QEMU Attach")},
    {"desc", N_("QEMU Attach")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_qemu_attach[] = {
    {"pid", VSH_OT_DATA, VSH_OFLAG_REQ, N_("pid")},
    {NULL, 0, 0, NULL}
};

static bool
cmdQemuAttach(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
    bool ret = false;
    unsigned int flags = 0;
18115
    unsigned int pid_value; /* API uses unsigned int, not pid_t */
18116 18117 18118 18119

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

18120
    if (vshCommandOptUInt(cmd, "pid", &pid_value) <= 0) {
18121 18122 18123 18124
        vshError(ctl, "%s", _("missing pid value"));
        goto cleanup;
    }

18125
    if (!(dom = virDomainQemuAttach(ctl->conn, pid_value, flags)))
18126 18127 18128 18129
        goto cleanup;

    if (dom != NULL) {
        vshPrint(ctl, _("Domain %s attached to pid %u\n"),
18130
                 virDomainGetName(dom), pid_value);
18131 18132 18133
        virDomainFree(dom);
        ret = true;
    } else {
18134
        vshError(ctl, _("Failed to attach to pid %u"), pid_value);
18135 18136 18137 18138 18139 18140
    }

cleanup:
    return ret;
}

18141
static const vshCmdDef domManagementCmds[] = {
18142 18143 18144 18145 18146 18147 18148
    {"attach-device", cmdAttachDevice, opts_attach_device,
     info_attach_device, 0},
    {"attach-disk", cmdAttachDisk, opts_attach_disk,
     info_attach_disk, 0},
    {"attach-interface", cmdAttachInterface, opts_attach_interface,
     info_attach_interface, 0},
    {"autostart", cmdAutostart, opts_autostart, info_autostart, 0},
L
Lei Li 已提交
18149
    {"blkdeviotune", cmdBlkdeviotune, opts_blkdeviotune, info_blkdeviotune, 0},
18150
    {"blkiotune", cmdBlkiotune, opts_blkiotune, info_blkiotune, 0},
E
Eric Blake 已提交
18151
    {"blockcopy", cmdBlockCopy, opts_block_copy, info_block_copy, 0},
18152
    {"blockjob", cmdBlockJob, opts_block_job, info_block_job, 0},
18153
    {"blockpull", cmdBlockPull, opts_block_pull, info_block_pull, 0},
18154
    {"blockresize", cmdBlockResize, opts_block_resize, info_block_resize, 0},
O
Osier Yang 已提交
18155
    {"change-media", cmdChangeMedia, opts_change_media, info_change_media, 0},
18156
#ifndef WIN32
18157
    {"console", cmdConsole, opts_console, info_console, 0},
18158
#endif
18159 18160
    {"cpu-baseline", cmdCPUBaseline, opts_cpu_baseline, info_cpu_baseline, 0},
    {"cpu-compare", cmdCPUCompare, opts_cpu_compare, info_cpu_compare, 0},
18161
    {"cpu-stats", cmdCPUStats, opts_cpu_stats, info_cpu_stats, 0},
18162 18163
    {"create", cmdCreate, opts_create, info_create, 0},
    {"define", cmdDefine, opts_define, info_define, 0},
18164
    {"desc", cmdDesc, opts_desc, info_desc, 0},
18165 18166 18167 18168 18169 18170
    {"destroy", cmdDestroy, opts_destroy, info_destroy, 0},
    {"detach-device", cmdDetachDevice, opts_detach_device,
     info_detach_device, 0},
    {"detach-disk", cmdDetachDisk, opts_detach_disk, info_detach_disk, 0},
    {"detach-interface", cmdDetachInterface, opts_detach_interface,
     info_detach_interface, 0},
18171
    {"domdisplay", cmdDomDisplay, opts_domdisplay, info_domdisplay, 0},
18172
    {"domid", cmdDomid, opts_domid, info_domid, 0},
18173
    {"domif-setlink", cmdDomIfSetLink, opts_domif_setlink, info_domif_setlink, 0},
18174
    {"domiftune", cmdDomIftune, opts_domiftune, info_domiftune, 0},
18175 18176 18177
    {"domjobabort", cmdDomjobabort, opts_domjobabort, info_domjobabort, 0},
    {"domjobinfo", cmdDomjobinfo, opts_domjobinfo, info_domjobinfo, 0},
    {"domname", cmdDomname, opts_domname, info_domname, 0},
18178 18179
    {"dompmsuspend", cmdDomPMSuspend,
     opts_dom_pm_suspend, info_dom_pm_suspend, 0},
18180 18181
    {"dompmwakeup", cmdDomPMWakeup,
     opts_dom_pm_wakeup, info_dom_pm_wakeup, 0},
18182 18183 18184 18185 18186 18187 18188 18189 18190
    {"domuuid", cmdDomuuid, opts_domuuid, info_domuuid, 0},
    {"domxml-from-native", cmdDomXMLFromNative, opts_domxmlfromnative,
     info_domxmlfromnative, 0},
    {"domxml-to-native", cmdDomXMLToNative, opts_domxmltonative,
     info_domxmltonative, 0},
    {"dump", cmdDump, opts_dump, info_dump, 0},
    {"dumpxml", cmdDumpXML, opts_dumpxml, info_dumpxml, 0},
    {"edit", cmdEdit, opts_edit, info_edit, 0},
    {"inject-nmi", cmdInjectNMI, opts_inject_nmi, info_inject_nmi, 0},
18191
    {"send-key", cmdSendKey, opts_send_key, info_send_key, 0},
18192 18193 18194 18195 18196 18197 18198 18199
    {"managedsave", cmdManagedSave, opts_managedsave, info_managedsave, 0},
    {"managedsave-remove", cmdManagedSaveRemove, opts_managedsaveremove,
     info_managedsaveremove, 0},
    {"maxvcpus", cmdMaxvcpus, opts_maxvcpus, info_maxvcpus, 0},
    {"memtune", cmdMemtune, opts_memtune, info_memtune, 0},
    {"migrate", cmdMigrate, opts_migrate, info_migrate, 0},
    {"migrate-setmaxdowntime", cmdMigrateSetMaxDowntime,
     opts_migrate_setmaxdowntime, info_migrate_setmaxdowntime, 0},
18200 18201
    {"migrate-setspeed", cmdMigrateSetMaxSpeed,
     opts_migrate_setspeed, info_migrate_setspeed, 0},
18202 18203
    {"migrate-getspeed", cmdMigrateGetMaxSpeed,
     opts_migrate_getspeed, info_migrate_getspeed, 0},
H
Hu Tao 已提交
18204
    {"numatune", cmdNumatune, opts_numatune, info_numatune, 0},
18205
    {"reboot", cmdReboot, opts_reboot, info_reboot, 0},
X
Xu He Jie 已提交
18206
    {"reset", cmdReset, opts_reset, info_reset, 0},
18207 18208 18209
    {"restore", cmdRestore, opts_restore, info_restore, 0},
    {"resume", cmdResume, opts_resume, info_resume, 0},
    {"save", cmdSave, opts_save, info_save, 0},
18210 18211 18212 18213 18214 18215
    {"save-image-define", cmdSaveImageDefine, opts_save_image_define,
     info_save_image_define, 0},
    {"save-image-dumpxml", cmdSaveImageDumpxml, opts_save_image_dumpxml,
     info_save_image_dumpxml, 0},
    {"save-image-edit", cmdSaveImageEdit, opts_save_image_edit,
     info_save_image_edit, 0},
18216
    {"schedinfo", cmdSchedinfo, opts_schedinfo, info_schedinfo, 0},
18217
    {"screenshot", cmdScreenshot, opts_screenshot, info_screenshot, 0},
18218 18219 18220 18221 18222 18223 18224 18225 18226 18227 18228 18229
    {"setmaxmem", cmdSetmaxmem, opts_setmaxmem, info_setmaxmem, 0},
    {"setmem", cmdSetmem, opts_setmem, info_setmem, 0},
    {"setvcpus", cmdSetvcpus, opts_setvcpus, info_setvcpus, 0},
    {"shutdown", cmdShutdown, opts_shutdown, info_shutdown, 0},
    {"start", cmdStart, opts_start, info_start, 0},
    {"suspend", cmdSuspend, opts_suspend, info_suspend, 0},
    {"ttyconsole", cmdTTYConsole, opts_ttyconsole, info_ttyconsole, 0},
    {"undefine", cmdUndefine, opts_undefine, info_undefine, 0},
    {"update-device", cmdUpdateDevice, opts_update_device,
     info_update_device, 0},
    {"vcpucount", cmdVcpucount, opts_vcpucount, info_vcpucount, 0},
    {"vcpuinfo", cmdVcpuinfo, opts_vcpuinfo, info_vcpuinfo, 0},
E
Eric Blake 已提交
18230
    {"vcpupin", cmdVcpuPin, opts_vcpupin, info_vcpupin, 0},
18231 18232
    {"vncdisplay", cmdVNCDisplay, opts_vncdisplay, info_vncdisplay, 0},
    {NULL, NULL, NULL, NULL, 0}
18233 18234 18235
};

static const vshCmdDef domMonitoringCmds[] = {
18236
    {"domblkerror", cmdDomBlkError, opts_domblkerror, info_domblkerror, 0},
18237
    {"domblkinfo", cmdDomblkinfo, opts_domblkinfo, info_domblkinfo, 0},
18238
    {"domblklist", cmdDomblklist, opts_domblklist, info_domblklist, 0},
18239
    {"domblkstat", cmdDomblkstat, opts_domblkstat, info_domblkstat, 0},
18240
    {"domcontrol", cmdDomControl, opts_domcontrol, info_domcontrol, 0},
18241
    {"domif-getlink", cmdDomIfGetLink, opts_domif_getlink, info_domif_getlink, 0},
18242
    {"domiflist", cmdDomiflist, opts_domiflist, info_domiflist, 0},
18243 18244 18245 18246 18247 18248
    {"domifstat", cmdDomIfstat, opts_domifstat, info_domifstat, 0},
    {"dominfo", cmdDominfo, opts_dominfo, info_dominfo, 0},
    {"dommemstat", cmdDomMemStat, opts_dommemstat, info_dommemstat, 0},
    {"domstate", cmdDomstate, opts_domstate, info_domstate, 0},
    {"list", cmdList, opts_list, info_list, 0},
    {NULL, NULL, NULL, NULL, 0}
18249 18250 18251
};

static const vshCmdDef storagePoolCmds[] = {
18252
    {"find-storage-pool-sources-as", cmdPoolDiscoverSourcesAs,
18253
     opts_find_storage_pool_sources_as, info_find_storage_pool_sources_as, 0},
18254
    {"find-storage-pool-sources", cmdPoolDiscoverSources,
18255 18256 18257 18258 18259 18260 18261 18262 18263 18264 18265 18266 18267 18268 18269 18270 18271 18272 18273 18274 18275
     opts_find_storage_pool_sources, info_find_storage_pool_sources, 0},
    {"pool-autostart", cmdPoolAutostart, opts_pool_autostart,
     info_pool_autostart, 0},
    {"pool-build", cmdPoolBuild, opts_pool_build, info_pool_build, 0},
    {"pool-create-as", cmdPoolCreateAs, opts_pool_X_as, info_pool_create_as, 0},
    {"pool-create", cmdPoolCreate, opts_pool_create, info_pool_create, 0},
    {"pool-define-as", cmdPoolDefineAs, opts_pool_X_as, info_pool_define_as, 0},
    {"pool-define", cmdPoolDefine, opts_pool_define, info_pool_define, 0},
    {"pool-delete", cmdPoolDelete, opts_pool_delete, info_pool_delete, 0},
    {"pool-destroy", cmdPoolDestroy, opts_pool_destroy, info_pool_destroy, 0},
    {"pool-dumpxml", cmdPoolDumpXML, opts_pool_dumpxml, info_pool_dumpxml, 0},
    {"pool-edit", cmdPoolEdit, opts_pool_edit, info_pool_edit, 0},
    {"pool-info", cmdPoolInfo, opts_pool_info, info_pool_info, 0},
    {"pool-list", cmdPoolList, opts_pool_list, info_pool_list, 0},
    {"pool-name", cmdPoolName, opts_pool_name, info_pool_name, 0},
    {"pool-refresh", cmdPoolRefresh, opts_pool_refresh, info_pool_refresh, 0},
    {"pool-start", cmdPoolStart, opts_pool_start, info_pool_start, 0},
    {"pool-undefine", cmdPoolUndefine, opts_pool_undefine,
     info_pool_undefine, 0},
    {"pool-uuid", cmdPoolUuid, opts_pool_uuid, info_pool_uuid, 0},
    {NULL, NULL, NULL, NULL, 0}
18276 18277 18278
};

static const vshCmdDef storageVolCmds[] = {
18279 18280 18281 18282 18283 18284 18285 18286 18287 18288 18289 18290 18291 18292 18293
    {"vol-clone", cmdVolClone, opts_vol_clone, info_vol_clone, 0},
    {"vol-create-as", cmdVolCreateAs, opts_vol_create_as,
     info_vol_create_as, 0},
    {"vol-create", cmdVolCreate, opts_vol_create, info_vol_create, 0},
    {"vol-create-from", cmdVolCreateFrom, opts_vol_create_from,
     info_vol_create_from, 0},
    {"vol-delete", cmdVolDelete, opts_vol_delete, info_vol_delete, 0},
    {"vol-download", cmdVolDownload, opts_vol_download, info_vol_download, 0},
    {"vol-dumpxml", cmdVolDumpXML, opts_vol_dumpxml, info_vol_dumpxml, 0},
    {"vol-info", cmdVolInfo, opts_vol_info, info_vol_info, 0},
    {"vol-key", cmdVolKey, opts_vol_key, info_vol_key, 0},
    {"vol-list", cmdVolList, opts_vol_list, info_vol_list, 0},
    {"vol-name", cmdVolName, opts_vol_name, info_vol_name, 0},
    {"vol-path", cmdVolPath, opts_vol_path, info_vol_path, 0},
    {"vol-pool", cmdVolPool, opts_vol_pool, info_vol_pool, 0},
18294
    {"vol-resize", cmdVolResize, opts_vol_resize, info_vol_resize, 0},
18295 18296 18297
    {"vol-upload", cmdVolUpload, opts_vol_upload, info_vol_upload, 0},
    {"vol-wipe", cmdVolWipe, opts_vol_wipe, info_vol_wipe, 0},
    {NULL, NULL, NULL, NULL, 0}
18298
};
18299

18300
static const vshCmdDef networkCmds[] = {
18301 18302 18303 18304 18305 18306 18307 18308 18309 18310 18311 18312 18313 18314 18315 18316 18317 18318 18319
    {"net-autostart", cmdNetworkAutostart, opts_network_autostart,
     info_network_autostart, 0},
    {"net-create", cmdNetworkCreate, opts_network_create,
     info_network_create, 0},
    {"net-define", cmdNetworkDefine, opts_network_define,
     info_network_define, 0},
    {"net-destroy", cmdNetworkDestroy, opts_network_destroy,
     info_network_destroy, 0},
    {"net-dumpxml", cmdNetworkDumpXML, opts_network_dumpxml,
     info_network_dumpxml, 0},
    {"net-edit", cmdNetworkEdit, opts_network_edit, info_network_edit, 0},
    {"net-info", cmdNetworkInfo, opts_network_info, info_network_info, 0},
    {"net-list", cmdNetworkList, opts_network_list, info_network_list, 0},
    {"net-name", cmdNetworkName, opts_network_name, info_network_name, 0},
    {"net-start", cmdNetworkStart, opts_network_start, info_network_start, 0},
    {"net-undefine", cmdNetworkUndefine, opts_network_undefine,
     info_network_undefine, 0},
    {"net-uuid", cmdNetworkUuid, opts_network_uuid, info_network_uuid, 0},
    {NULL, NULL, NULL, NULL, 0}
18320
};
18321

18322
static const vshCmdDef nodedevCmds[] = {
18323 18324 18325 18326
    {"nodedev-create", cmdNodeDeviceCreate, opts_node_device_create,
     info_node_device_create, 0},
    {"nodedev-destroy", cmdNodeDeviceDestroy, opts_node_device_destroy,
     info_node_device_destroy, 0},
18327 18328 18329 18330
    {"nodedev-detach", cmdNodeDeviceDetach, opts_node_device_detach,
     info_node_device_detach, 0},
    {"nodedev-dettach", cmdNodeDeviceDetach, opts_node_device_detach,
     info_node_device_detach, VSH_CMD_FLAG_ALIAS},
18331 18332 18333 18334 18335 18336 18337 18338 18339
    {"nodedev-dumpxml", cmdNodeDeviceDumpXML, opts_node_device_dumpxml,
     info_node_device_dumpxml, 0},
    {"nodedev-list", cmdNodeListDevices, opts_node_list_devices,
     info_node_list_devices, 0},
    {"nodedev-reattach", cmdNodeDeviceReAttach, opts_node_device_reattach,
     info_node_device_reattach, 0},
    {"nodedev-reset", cmdNodeDeviceReset, opts_node_device_reset,
     info_node_device_reset, 0},
    {NULL, NULL, NULL, NULL, 0}
18340 18341 18342
};

static const vshCmdDef ifaceCmds[] = {
E
Eric Blake 已提交
18343 18344
    {"iface-begin", cmdInterfaceBegin, opts_interface_begin,
     info_interface_begin, 0},
18345 18346
    {"iface-bridge", cmdInterfaceBridge, opts_interface_bridge,
     info_interface_bridge, 0},
E
Eric Blake 已提交
18347 18348
    {"iface-commit", cmdInterfaceCommit, opts_interface_commit,
     info_interface_commit, 0},
18349 18350 18351 18352 18353 18354 18355 18356 18357 18358 18359 18360 18361 18362
    {"iface-define", cmdInterfaceDefine, opts_interface_define,
     info_interface_define, 0},
    {"iface-destroy", cmdInterfaceDestroy, opts_interface_destroy,
     info_interface_destroy, 0},
    {"iface-dumpxml", cmdInterfaceDumpXML, opts_interface_dumpxml,
     info_interface_dumpxml, 0},
    {"iface-edit", cmdInterfaceEdit, opts_interface_edit,
     info_interface_edit, 0},
    {"iface-list", cmdInterfaceList, opts_interface_list,
     info_interface_list, 0},
    {"iface-mac", cmdInterfaceMAC, opts_interface_mac,
     info_interface_mac, 0},
    {"iface-name", cmdInterfaceName, opts_interface_name,
     info_interface_name, 0},
E
Eric Blake 已提交
18363 18364
    {"iface-rollback", cmdInterfaceRollback, opts_interface_rollback,
     info_interface_rollback, 0},
18365 18366
    {"iface-start", cmdInterfaceStart, opts_interface_start,
     info_interface_start, 0},
18367 18368
    {"iface-unbridge", cmdInterfaceUnbridge, opts_interface_unbridge,
     info_interface_unbridge, 0},
18369 18370 18371
    {"iface-undefine", cmdInterfaceUndefine, opts_interface_undefine,
     info_interface_undefine, 0},
    {NULL, NULL, NULL, NULL, 0}
18372
};
18373

18374
static const vshCmdDef nwfilterCmds[] = {
18375 18376 18377 18378 18379 18380 18381 18382 18383 18384 18385
    {"nwfilter-define", cmdNWFilterDefine, opts_nwfilter_define,
     info_nwfilter_define, 0},
    {"nwfilter-dumpxml", cmdNWFilterDumpXML, opts_nwfilter_dumpxml,
     info_nwfilter_dumpxml, 0},
    {"nwfilter-edit", cmdNWFilterEdit, opts_nwfilter_edit,
     info_nwfilter_edit, 0},
    {"nwfilter-list", cmdNWFilterList, opts_nwfilter_list,
     info_nwfilter_list, 0},
    {"nwfilter-undefine", cmdNWFilterUndefine, opts_nwfilter_undefine,
     info_nwfilter_undefine, 0},
    {NULL, NULL, NULL, NULL, 0}
18386
};
18387

18388
static const vshCmdDef secretCmds[] = {
18389 18390 18391 18392 18393 18394 18395 18396 18397 18398 18399 18400
    {"secret-define", cmdSecretDefine, opts_secret_define,
     info_secret_define, 0},
    {"secret-dumpxml", cmdSecretDumpXML, opts_secret_dumpxml,
     info_secret_dumpxml, 0},
    {"secret-get-value", cmdSecretGetValue, opts_secret_get_value,
     info_secret_get_value, 0},
    {"secret-list", cmdSecretList, NULL, info_secret_list, 0},
    {"secret-set-value", cmdSecretSetValue, opts_secret_set_value,
     info_secret_set_value, 0},
    {"secret-undefine", cmdSecretUndefine, opts_secret_undefine,
     info_secret_undefine, 0},
    {NULL, NULL, NULL, NULL, 0}
18401
};
18402

18403
static const vshCmdDef virshCmds[] = {
18404 18405 18406 18407 18408 18409 18410
    {"cd", cmdCd, opts_cd, info_cd, VSH_CMD_FLAG_NOCONNECT},
    {"echo", cmdEcho, opts_echo, info_echo, VSH_CMD_FLAG_NOCONNECT},
    {"exit", cmdQuit, NULL, info_quit, VSH_CMD_FLAG_NOCONNECT},
    {"help", cmdHelp, opts_help, info_help, VSH_CMD_FLAG_NOCONNECT},
    {"pwd", cmdPwd, NULL, info_pwd, VSH_CMD_FLAG_NOCONNECT},
    {"quit", cmdQuit, NULL, info_quit, VSH_CMD_FLAG_NOCONNECT},
    {NULL, NULL, NULL, NULL, 0}
18411
};
18412

18413
static const vshCmdDef snapshotCmds[] = {
18414 18415
    {"snapshot-create", cmdSnapshotCreate, opts_snapshot_create,
     info_snapshot_create, 0},
18416 18417
    {"snapshot-create-as", cmdSnapshotCreateAs, opts_snapshot_create_as,
     info_snapshot_create_as, 0},
18418 18419 18420 18421 18422 18423
    {"snapshot-current", cmdSnapshotCurrent, opts_snapshot_current,
     info_snapshot_current, 0},
    {"snapshot-delete", cmdSnapshotDelete, opts_snapshot_delete,
     info_snapshot_delete, 0},
    {"snapshot-dumpxml", cmdSnapshotDumpXML, opts_snapshot_dumpxml,
     info_snapshot_dumpxml, 0},
18424 18425
    {"snapshot-edit", cmdSnapshotEdit, opts_snapshot_edit,
     info_snapshot_edit, 0},
E
Eric Blake 已提交
18426 18427
    {"snapshot-info", cmdSnapshotInfo, opts_snapshot_info,
     info_snapshot_info, 0},
18428 18429
    {"snapshot-list", cmdSnapshotList, opts_snapshot_list,
     info_snapshot_list, 0},
E
Eric Blake 已提交
18430 18431
    {"snapshot-parent", cmdSnapshotParent, opts_snapshot_parent,
     info_snapshot_parent, 0},
18432 18433 18434
    {"snapshot-revert", cmdDomainSnapshotRevert, opts_snapshot_revert,
     info_snapshot_revert, 0},
    {NULL, NULL, NULL, NULL, 0}
18435
};
18436

18437
static const vshCmdDef hostAndHypervisorCmds[] = {
18438 18439 18440 18441 18442
    {"capabilities", cmdCapabilities, NULL, info_capabilities, 0},
    {"connect", cmdConnect, opts_connect, info_connect,
     VSH_CMD_FLAG_NOCONNECT},
    {"freecell", cmdFreecell, opts_freecell, info_freecell, 0},
    {"hostname", cmdHostname, NULL, info_hostname, 0},
18443
    {"nodecpustats", cmdNodeCpuStats, opts_node_cpustats, info_nodecpustats, 0},
18444
    {"nodeinfo", cmdNodeinfo, NULL, info_nodeinfo, 0},
18445
    {"nodememstats", cmdNodeMemStats, opts_node_memstats, info_nodememstats, 0},
18446
    {"nodesuspend", cmdNodeSuspend, opts_node_suspend, info_nodesuspend, 0},
18447
    {"qemu-attach", cmdQemuAttach, opts_qemu_attach, info_qemu_attach, 0},
18448 18449 18450 18451
    {"qemu-monitor-command", cmdQemuMonitorCommand, opts_qemu_monitor_command,
     info_qemu_monitor_command, 0},
    {"sysinfo", cmdSysinfo, NULL, info_sysinfo, 0},
    {"uri", cmdURI, NULL, info_uri, 0},
18452
    {"version", cmdVersion, opts_version, info_version, 0},
18453
    {NULL, NULL, NULL, NULL, 0}
K
Karel Zak 已提交
18454 18455
};

18456 18457 18458 18459 18460 18461 18462 18463 18464 18465 18466 18467 18468 18469 18470 18471 18472
static const vshCmdGrp cmdGroups[] = {
    {VSH_CMD_GRP_DOM_MANAGEMENT, "domain", domManagementCmds},
    {VSH_CMD_GRP_DOM_MONITORING, "monitor", domMonitoringCmds},
    {VSH_CMD_GRP_HOST_AND_HV, "host", hostAndHypervisorCmds},
    {VSH_CMD_GRP_IFACE, "interface", ifaceCmds},
    {VSH_CMD_GRP_NWFILTER, "filter", nwfilterCmds},
    {VSH_CMD_GRP_NETWORK, "network", networkCmds},
    {VSH_CMD_GRP_NODEDEV, "nodedev", nodedevCmds},
    {VSH_CMD_GRP_SECRET, "secret", secretCmds},
    {VSH_CMD_GRP_SNAPSHOT, "snapshot", snapshotCmds},
    {VSH_CMD_GRP_STORAGE_POOL, "pool", storagePoolCmds},
    {VSH_CMD_GRP_STORAGE_VOL, "volume", storageVolCmds},
    {VSH_CMD_GRP_VIRSH, "virsh", virshCmds},
    {NULL, NULL, NULL}
};


K
Karel Zak 已提交
18473 18474 18475 18476
/* ---------------
 * Utils for work with command definition
 * ---------------
 */
K
Karel Zak 已提交
18477
static const char *
18478
vshCmddefGetInfo(const vshCmdDef * cmd, const char *name)
18479
{
18480
    const vshCmdInfo *info;
18481

K
Karel Zak 已提交
18482
    for (info = cmd->info; info && info->name; info++) {
18483
        if (STREQ(info->name, name))
K
Karel Zak 已提交
18484 18485 18486 18487 18488
            return info->data;
    }
    return NULL;
}

18489
/* Validate that the options associated with cmd can be parsed.  */
18490
static int
E
Eric Blake 已提交
18491
vshCmddefOptParse(const vshCmdDef *cmd, uint32_t *opts_need_arg,
18492 18493 18494 18495 18496
                  uint32_t *opts_required)
{
    int i;
    bool optional = false;

E
Eric Blake 已提交
18497 18498 18499
    *opts_need_arg = 0;
    *opts_required = 0;

18500 18501 18502 18503 18504 18505 18506 18507 18508
    if (!cmd->opts)
        return 0;

    for (i = 0; cmd->opts[i].name; i++) {
        const vshCmdOptDef *opt = &cmd->opts[i];

        if (i > 31)
            return -1; /* too many options */
        if (opt->type == VSH_OT_BOOL) {
E
Eric Blake 已提交
18509
            if (opt->flags & VSH_OFLAG_REQ)
18510 18511 18512
                return -1; /* bool options can't be mandatory */
            continue;
        }
E
Eric Blake 已提交
18513 18514 18515 18516 18517 18518 18519 18520 18521 18522 18523 18524
        if (opt->type == VSH_OT_ALIAS) {
            int j;
            if (opt->flags || !opt->help)
                return -1; /* alias options are tracked by the original name */
            for (j = i + 1; cmd->opts[j].name; j++) {
                if (STREQ(opt->help, cmd->opts[j].name))
                    break;
            }
            if (!cmd->opts[j].name)
                return -1; /* alias option must map to a later option name */
            continue;
        }
E
Eric Blake 已提交
18525 18526
        if (opt->flags & VSH_OFLAG_REQ_OPT) {
            if (opt->flags & VSH_OFLAG_REQ)
L
Lai Jiangshan 已提交
18527 18528 18529 18530
                *opts_required |= 1 << i;
            continue;
        }

18531
        *opts_need_arg |= 1 << i;
E
Eric Blake 已提交
18532
        if (opt->flags & VSH_OFLAG_REQ) {
18533 18534 18535 18536 18537 18538
            if (optional)
                return -1; /* mandatory options must be listed first */
            *opts_required |= 1 << i;
        } else {
            optional = true;
        }
18539 18540 18541

        if (opt->type == VSH_OT_ARGV && cmd->opts[i + 1].name)
            return -1; /* argv option must be listed last */
18542 18543 18544 18545
    }
    return 0;
}

18546
static const vshCmdOptDef *
18547
vshCmddefGetOption(vshControl *ctl, const vshCmdDef *cmd, const char *name,
18548
                   uint32_t *opts_seen, int *opt_index)
18549
{
18550 18551 18552 18553
    int i;

    for (i = 0; cmd->opts && cmd->opts[i].name; i++) {
        const vshCmdOptDef *opt = &cmd->opts[i];
18554

18555
        if (STREQ(opt->name, name)) {
E
Eric Blake 已提交
18556 18557 18558 18559
            if (opt->type == VSH_OT_ALIAS) {
                name = opt->help;
                continue;
            }
18560
            if ((*opts_seen & (1 << i)) && opt->type != VSH_OT_ARGV) {
18561 18562 18563
                vshError(ctl, _("option --%s already seen"), name);
                return NULL;
            }
18564 18565
            *opts_seen |= 1 << i;
            *opt_index = i;
K
Karel Zak 已提交
18566
            return opt;
18567 18568 18569 18570 18571
        }
    }

    vshError(ctl, _("command '%s' doesn't support option --%s"),
             cmd->name, name);
K
Karel Zak 已提交
18572 18573 18574
    return NULL;
}

18575
static const vshCmdOptDef *
18576 18577
vshCmddefGetData(const vshCmdDef *cmd, uint32_t *opts_need_arg,
                 uint32_t *opts_seen)
18578
{
18579
    int i;
18580
    const vshCmdOptDef *opt;
K
Karel Zak 已提交
18581

18582 18583 18584 18585
    if (!*opts_need_arg)
        return NULL;

    /* Grab least-significant set bit */
E
Eric Blake 已提交
18586
    i = ffs(*opts_need_arg) - 1;
18587
    opt = &cmd->opts[i];
18588
    if (opt->type != VSH_OT_ARGV)
18589
        *opts_need_arg &= ~(1 << i);
18590
    *opts_seen |= 1 << i;
18591
    return opt;
K
Karel Zak 已提交
18592 18593
}

18594 18595 18596
/*
 * Checks for required options
 */
18597
static int
18598 18599
vshCommandCheckOpts(vshControl *ctl, const vshCmd *cmd, uint32_t opts_required,
                    uint32_t opts_seen)
18600
{
18601
    const vshCmdDef *def = cmd->def;
18602 18603 18604 18605 18606 18607 18608 18609 18610
    int i;

    opts_required &= ~opts_seen;
    if (!opts_required)
        return 0;

    for (i = 0; def->opts[i].name; i++) {
        if (opts_required & (1 << i)) {
            const vshCmdOptDef *opt = &def->opts[i];
18611

18612
            vshError(ctl,
18613
                     opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV ?
18614 18615 18616
                     _("command '%s' requires <%s> option") :
                     _("command '%s' requires --%s option"),
                     def->name, opt->name);
18617 18618
        }
    }
18619
    return -1;
18620 18621
}

18622
static const vshCmdDef *
18623 18624
vshCmddefSearch(const char *cmdname)
{
18625
    const vshCmdGrp *g;
18626
    const vshCmdDef *c;
18627

18628 18629
    for (g = cmdGroups; g->name; g++) {
        for (c = g->commands; c->name; c++) {
18630
            if (STREQ(c->name, cmdname))
18631 18632 18633 18634
                return c;
        }
    }

K
Karel Zak 已提交
18635 18636 18637
    return NULL;
}

18638 18639 18640 18641 18642 18643
static const vshCmdGrp *
vshCmdGrpSearch(const char *grpname)
{
    const vshCmdGrp *g;

    for (g = cmdGroups; g->name; g++) {
18644
        if (STREQ(g->name, grpname) || STREQ(g->keyword, grpname))
18645 18646 18647 18648 18649 18650
            return g;
    }

    return NULL;
}

E
Eric Blake 已提交
18651
static bool
18652 18653 18654 18655 18656 18657 18658
vshCmdGrpHelp(vshControl *ctl, const char *grpname)
{
    const vshCmdGrp *grp = vshCmdGrpSearch(grpname);
    const vshCmdDef *cmd = NULL;

    if (!grp) {
        vshError(ctl, _("command group '%s' doesn't exist"), grpname);
E
Eric Blake 已提交
18659
        return false;
18660 18661 18662 18663 18664 18665 18666 18667 18668 18669
    } else {
        vshPrint(ctl, _(" %s (help keyword '%s'):\n"), grp->name,
                 grp->keyword);

        for (cmd = grp->commands; cmd->name; cmd++) {
            vshPrint(ctl, "    %-30s %s\n", cmd->name,
                     _(vshCmddefGetInfo(cmd, "help")));
        }
    }

E
Eric Blake 已提交
18670
    return true;
18671 18672
}

E
Eric Blake 已提交
18673
static bool
18674
vshCmddefHelp(vshControl *ctl, const char *cmdname)
18675
{
18676
    const vshCmdDef *def = vshCmddefSearch(cmdname);
18677

K
Karel Zak 已提交
18678
    if (!def) {
18679
        vshError(ctl, _("command '%s' doesn't exist"), cmdname);
E
Eric Blake 已提交
18680
        return false;
18681
    } else {
E
Eric Blake 已提交
18682 18683
        /* Don't translate desc if it is "".  */
        const char *desc = vshCmddefGetInfo(def, "desc");
E
Eric Blake 已提交
18684
        const char *help = _(vshCmddefGetInfo(def, "help"));
18685
        char buf[256];
18686 18687
        uint32_t opts_need_arg;
        uint32_t opts_required;
18688
        bool shortopt = false; /* true if 'arg' works instead of '--opt arg' */
18689 18690 18691 18692

        if (vshCmddefOptParse(def, &opts_need_arg, &opts_required)) {
            vshError(ctl, _("internal error: bad options in command: '%s'"),
                     def->name);
E
Eric Blake 已提交
18693
            return false;
18694
        }
K
Karel Zak 已提交
18695

18696
        fputs(_("  NAME\n"), stdout);
18697 18698
        fprintf(stdout, "    %s - %s\n", def->name, help);

18699 18700 18701 18702 18703
        fputs(_("\n  SYNOPSIS\n"), stdout);
        fprintf(stdout, "    %s", def->name);
        if (def->opts) {
            const vshCmdOptDef *opt;
            for (opt = def->opts; opt->name; opt++) {
18704
                const char *fmt = "%s";
18705 18706
                switch (opt->type) {
                case VSH_OT_BOOL:
18707
                    fmt = "[--%s]";
18708 18709
                    break;
                case VSH_OT_INT:
E
Eric Blake 已提交
18710
                    /* xgettext:c-format */
E
Eric Blake 已提交
18711
                    fmt = ((opt->flags & VSH_OFLAG_REQ) ? "<%s>"
18712
                           : _("[--%s <number>]"));
18713 18714
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
18715 18716
                    break;
                case VSH_OT_STRING:
E
Eric Blake 已提交
18717 18718
                    /* xgettext:c-format */
                    fmt = _("[--%s <string>]");
18719 18720
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
18721 18722
                    break;
                case VSH_OT_DATA:
E
Eric Blake 已提交
18723
                    fmt = ((opt->flags & VSH_OFLAG_REQ) ? "<%s>" : "[<%s>]");
18724 18725
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
18726 18727 18728
                    break;
                case VSH_OT_ARGV:
                    /* xgettext:c-format */
18729 18730 18731 18732 18733 18734 18735 18736
                    if (shortopt) {
                        fmt = (opt->flags & VSH_OFLAG_REQ)
                            ? _("{[--%s] <string>}...")
                            : _("[[--%s] <string>]...");
                    } else {
                        fmt = (opt->flags & VSH_OFLAG_REQ) ? _("<%s>...")
                            : _("[<%s>]...");
                    }
18737
                    break;
E
Eric Blake 已提交
18738 18739 18740
                case VSH_OT_ALIAS:
                    /* aliases are intentionally undocumented */
                    continue;
18741
                default:
18742
                    assert(0);
18743
                }
18744
                fputc(' ', stdout);
E
Eric Blake 已提交
18745
                fprintf(stdout, fmt, opt->name);
18746
            }
K
Karel Zak 已提交
18747
        }
18748 18749 18750
        fputc('\n', stdout);

        if (desc[0]) {
18751
            /* Print the description only if it's not empty.  */
18752
            fputs(_("\n  DESCRIPTION\n"), stdout);
E
Eric Blake 已提交
18753
            fprintf(stdout, "    %s\n", _(desc));
K
Karel Zak 已提交
18754
        }
18755

K
Karel Zak 已提交
18756
        if (def->opts) {
18757
            const vshCmdOptDef *opt;
18758
            fputs(_("\n  OPTIONS\n"), stdout);
18759
            for (opt = def->opts; opt->name; opt++) {
18760 18761
                switch (opt->type) {
                case VSH_OT_BOOL:
K
Karel Zak 已提交
18762
                    snprintf(buf, sizeof(buf), "--%s", opt->name);
18763 18764
                    break;
                case VSH_OT_INT:
18765
                    snprintf(buf, sizeof(buf),
E
Eric Blake 已提交
18766
                             (opt->flags & VSH_OFLAG_REQ) ? _("[--%s] <number>")
18767
                             : _("--%s <number>"), opt->name);
18768 18769
                    break;
                case VSH_OT_STRING:
18770
                    /* OT_STRING should never be VSH_OFLAG_REQ */
18771
                    snprintf(buf, sizeof(buf), _("--%s <string>"), opt->name);
18772 18773
                    break;
                case VSH_OT_DATA:
18774 18775
                    snprintf(buf, sizeof(buf), _("[--%s] <string>"),
                             opt->name);
18776 18777
                    break;
                case VSH_OT_ARGV:
18778 18779 18780
                    snprintf(buf, sizeof(buf),
                             shortopt ? _("[--%s] <string>") : _("<%s>"),
                             opt->name);
18781
                    break;
E
Eric Blake 已提交
18782 18783
                case VSH_OT_ALIAS:
                    continue;
18784 18785 18786
                default:
                    assert(0);
                }
18787

E
Eric Blake 已提交
18788
                fprintf(stdout, "    %-15s  %s\n", buf, _(opt->help));
18789
            }
K
Karel Zak 已提交
18790 18791 18792
        }
        fputc('\n', stdout);
    }
E
Eric Blake 已提交
18793
    return true;
K
Karel Zak 已提交
18794 18795 18796 18797 18798 18799
}

/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
18800 18801 18802
static void
vshCommandOptFree(vshCmdOpt * arg)
{
K
Karel Zak 已提交
18803 18804
    vshCmdOpt *a = arg;

18805
    while (a) {
K
Karel Zak 已提交
18806
        vshCmdOpt *tmp = a;
18807

K
Karel Zak 已提交
18808 18809
        a = a->next;

18810 18811
        VIR_FREE(tmp->data);
        VIR_FREE(tmp);
K
Karel Zak 已提交
18812 18813 18814 18815
    }
}

static void
18816
vshCommandFree(vshCmd *cmd)
18817
{
K
Karel Zak 已提交
18818 18819
    vshCmd *c = cmd;

18820
    while (c) {
K
Karel Zak 已提交
18821
        vshCmd *tmp = c;
18822

K
Karel Zak 已提交
18823 18824 18825 18826
        c = c->next;

        if (tmp->opts)
            vshCommandOptFree(tmp->opts);
18827
        VIR_FREE(tmp);
K
Karel Zak 已提交
18828 18829 18830
    }
}

E
Eric Blake 已提交
18831 18832 18833 18834 18835 18836 18837 18838 18839 18840 18841
/**
 * vshCommandOpt:
 * @cmd: parsed command line to search
 * @name: option name to search for
 * @opt: result of the search
 *
 * Look up an option passed to CMD by NAME.  Returns 1 with *OPT set
 * to the option if found, 0 with *OPT set to NULL if the name is
 * valid and the option is not required, -1 with *OPT set to NULL if
 * the option is required but not present, and -2 if NAME is not valid
 * (-2 indicates a programming error).  No error messages are issued.
K
Karel Zak 已提交
18842
 */
E
Eric Blake 已提交
18843 18844
static int
vshCommandOpt(const vshCmd *cmd, const char *name, vshCmdOpt **opt)
18845
{
E
Eric Blake 已提交
18846 18847
    vshCmdOpt *candidate = cmd->opts;
    const vshCmdOptDef *valid = cmd->def->opts;
18848

E
Eric Blake 已提交
18849 18850 18851 18852 18853 18854 18855
    /* See if option is present on command line.  */
    while (candidate) {
        if (STREQ(candidate->def->name, name)) {
            *opt = candidate;
            return 1;
        }
        candidate = candidate->next;
K
Karel Zak 已提交
18856
    }
E
Eric Blake 已提交
18857 18858 18859 18860 18861 18862 18863

    /* Option not present, see if command requires it.  */
    *opt = NULL;
    while (valid) {
        if (!valid->name)
            break;
        if (STREQ(name, valid->name))
E
Eric Blake 已提交
18864
            return (valid->flags & VSH_OFLAG_REQ) == 0 ? 0 : -1;
E
Eric Blake 已提交
18865 18866 18867 18868
        valid++;
    }
    /* If we got here, the name is unknown.  */
    return -2;
K
Karel Zak 已提交
18869 18870
}

E
Eric Blake 已提交
18871 18872
/**
 * vshCommandOptInt:
18873 18874 18875 18876 18877 18878 18879
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Convert option to int
 * Return value:
 * >0 if option found and valid (@value updated)
E
Eric Blake 已提交
18880
 * 0 if option not found and not required (@value untouched)
18881
 * <0 in all other cases (@value untouched)
K
Karel Zak 已提交
18882 18883
 */
static int
18884
vshCommandOptInt(const vshCmd *cmd, const char *name, int *value)
18885
{
E
Eric Blake 已提交
18886 18887
    vshCmdOpt *arg;
    int ret;
18888

E
Eric Blake 已提交
18889 18890 18891 18892 18893 18894 18895
    ret = vshCommandOpt(cmd, name, &arg);
    if (ret <= 0)
        return ret;
    if (!arg->data) {
        /* only possible on bool, but if name is bool, this is a
         * programming bug */
        return -2;
18896
    }
E
Eric Blake 已提交
18897

E
Eric Blake 已提交
18898 18899 18900
    if (virStrToLong_i(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
K
Karel Zak 已提交
18901 18902
}

18903

E
Eric Blake 已提交
18904 18905 18906 18907 18908 18909
/**
 * vshCommandOptUInt:
 * @cmd command reference
 * @name option name
 * @value result
 *
18910 18911 18912 18913 18914 18915
 * Convert option to unsigned int
 * See vshCommandOptInt()
 */
static int
vshCommandOptUInt(const vshCmd *cmd, const char *name, unsigned int *value)
{
E
Eric Blake 已提交
18916 18917
    vshCmdOpt *arg;
    int ret;
18918

E
Eric Blake 已提交
18919 18920 18921 18922 18923 18924 18925
    ret = vshCommandOpt(cmd, name, &arg);
    if (ret <= 0)
        return ret;
    if (!arg->data) {
        /* only possible on bool, but if name is bool, this is a
         * programming bug */
        return -2;
18926
    }
E
Eric Blake 已提交
18927

E
Eric Blake 已提交
18928 18929 18930
    if (virStrToLong_ui(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
18931 18932 18933
}


18934
/*
E
Eric Blake 已提交
18935 18936 18937 18938 18939
 * vshCommandOptUL:
 * @cmd command reference
 * @name option name
 * @value result
 *
18940 18941 18942 18943 18944
 * Convert option to unsigned long
 * See vshCommandOptInt()
 */
static int
vshCommandOptUL(const vshCmd *cmd, const char *name, unsigned long *value)
18945
{
E
Eric Blake 已提交
18946 18947
    vshCmdOpt *arg;
    int ret;
18948

E
Eric Blake 已提交
18949 18950 18951 18952 18953 18954 18955
    ret = vshCommandOpt(cmd, name, &arg);
    if (ret <= 0)
        return ret;
    if (!arg->data) {
        /* only possible on bool, but if name is bool, this is a
         * programming bug */
        return -2;
18956
    }
E
Eric Blake 已提交
18957

E
Eric Blake 已提交
18958 18959 18960
    if (virStrToLong_ul(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
18961 18962
}

E
Eric Blake 已提交
18963 18964 18965 18966 18967 18968
/**
 * vshCommandOptString:
 * @cmd command reference
 * @name option name
 * @value result
 *
K
Karel Zak 已提交
18969
 * Returns option as STRING
E
Eric Blake 已提交
18970 18971 18972 18973
 * Return value:
 * >0 if option found and valid (@value updated)
 * 0 if option not found and not required (@value untouched)
 * <0 in all other cases (@value untouched)
K
Karel Zak 已提交
18974
 */
18975 18976
static int
vshCommandOptString(const vshCmd *cmd, const char *name, const char **value)
18977
{
E
Eric Blake 已提交
18978 18979 18980 18981 18982 18983 18984 18985 18986 18987
    vshCmdOpt *arg;
    int ret;

    ret = vshCommandOpt(cmd, name, &arg);
    if (ret <= 0)
        return ret;
    if (!arg->data) {
        /* only possible on bool, but if name is bool, this is a
         * programming bug */
        return -2;
18988
    }
18989

E
Eric Blake 已提交
18990
    if (!*arg->data && !(arg->def->flags & VSH_OFLAG_EMPTY_OK)) {
E
Eric Blake 已提交
18991 18992 18993 18994
        return -1;
    }
    *value = arg->data;
    return 1;
K
Karel Zak 已提交
18995 18996
}

E
Eric Blake 已提交
18997 18998 18999 19000 19001 19002
/**
 * vshCommandOptLongLong:
 * @cmd command reference
 * @name option name
 * @value result
 *
19003
 * Returns option as long long
19004
 * See vshCommandOptInt()
19005
 */
19006 19007 19008
static int
vshCommandOptLongLong(const vshCmd *cmd, const char *name,
                      long long *value)
19009
{
E
Eric Blake 已提交
19010 19011
    vshCmdOpt *arg;
    int ret;
19012

E
Eric Blake 已提交
19013 19014 19015 19016 19017 19018 19019
    ret = vshCommandOpt(cmd, name, &arg);
    if (ret <= 0)
        return ret;
    if (!arg->data) {
        /* only possible on bool, but if name is bool, this is a
         * programming bug */
        return -2;
19020
    }
E
Eric Blake 已提交
19021

E
Eric Blake 已提交
19022 19023 19024
    if (virStrToLong_ll(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
19025 19026
}

E
Eric Blake 已提交
19027 19028 19029 19030 19031 19032 19033 19034 19035
/**
 * vshCommandOptULongLong:
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Returns option as long long
 * See vshCommandOptInt()
 */
19036 19037 19038 19039
static int
vshCommandOptULongLong(const vshCmd *cmd, const char *name,
                       unsigned long long *value)
{
E
Eric Blake 已提交
19040 19041
    vshCmdOpt *arg;
    int ret;
19042

E
Eric Blake 已提交
19043 19044 19045 19046 19047 19048 19049
    ret = vshCommandOpt(cmd, name, &arg);
    if (ret <= 0)
        return ret;
    if (!arg->data) {
        /* only possible on bool, but if name is bool, this is a
         * programming bug */
        return -2;
19050
    }
E
Eric Blake 已提交
19051

E
Eric Blake 已提交
19052 19053 19054
    if (virStrToLong_ull(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
19055 19056 19057
}


E
Eric Blake 已提交
19058 19059 19060 19061 19062 19063 19064 19065 19066 19067 19068 19069 19070 19071 19072 19073 19074 19075 19076 19077 19078 19079 19080 19081 19082 19083 19084 19085 19086 19087
/**
 * vshCommandOptScaledInt:
 * @cmd command reference
 * @name option name
 * @value result
 * @scale default of 1 or 1024, if no suffix is present
 * @max maximum value permitted
 *
 * Returns option as long long, scaled according to suffix
 * See vshCommandOptInt()
 */
static int
vshCommandOptScaledInt(const vshCmd *cmd, const char *name,
                       unsigned long long *value, int scale,
                       unsigned long long max)
{
    const char *str;
    int ret;
    char *end;

    ret = vshCommandOptString(cmd, name, &str);
    if (ret <= 0)
        return ret;
    if (virStrToLong_ull(str, &end, 10, value) < 0 ||
        virScaleInteger(value, end, scale, max) < 0)
        return -1;
    return 1;
}


E
Eric Blake 已提交
19088 19089 19090 19091 19092 19093 19094 19095 19096
/**
 * vshCommandOptBool:
 * @cmd command reference
 * @name option name
 *
 * Returns true/false if the option exists.  Note that this does NOT
 * validate whether the option is actually boolean, or even whether
 * name is legal; so that this can be used to probe whether a data
 * option is present without actually using that data.
K
Karel Zak 已提交
19097
 */
E
Eric Blake 已提交
19098
static bool
19099
vshCommandOptBool(const vshCmd *cmd, const char *name)
19100
{
E
Eric Blake 已提交
19101 19102 19103
    vshCmdOpt *dummy;

    return vshCommandOpt(cmd, name, &dummy) == 1;
K
Karel Zak 已提交
19104 19105
}

E
Eric Blake 已提交
19106 19107 19108 19109 19110
/**
 * vshCommandOptArgv:
 * @cmd command reference
 * @opt starting point for the search
 *
19111 19112
 * Returns the next argv argument after OPT (or the first one if OPT
 * is NULL), or NULL if no more are present.
19113
 *
19114
 * Requires that a VSH_OT_ARGV option be last in the
19115 19116
 * list of supported options in CMD->def->opts.
 */
19117 19118
static const vshCmdOpt *
vshCommandOptArgv(const vshCmd *cmd, const vshCmdOpt *opt)
19119
{
19120
    opt = opt ? opt->next : cmd->opts;
19121 19122

    while (opt) {
E
Eric Blake 已提交
19123
        if (opt->def->type == VSH_OT_ARGV) {
19124
            return opt;
19125 19126 19127 19128 19129 19130
        }
        opt = opt->next;
    }
    return NULL;
}

J
Jim Meyering 已提交
19131 19132 19133 19134 19135 19136 19137 19138 19139 19140 19141 19142 19143 19144 19145 19146 19147 19148
/* Determine whether CMD->opts includes an option with name OPTNAME.
   If not, give a diagnostic and return false.
   If so, return true.  */
static bool
cmd_has_option (vshControl *ctl, const vshCmd *cmd, const char *optname)
{
    /* Iterate through cmd->opts, to ensure that there is an entry
       with name OPTNAME and type VSH_OT_DATA. */
    bool found = false;
    const vshCmdOpt *opt;
    for (opt = cmd->opts; opt; opt = opt->next) {
        if (STREQ (opt->def->name, optname) && opt->def->type == VSH_OT_DATA) {
            found = true;
            break;
        }
    }

    if (!found)
19149
        vshError(ctl, _("internal error: virsh %s: no %s VSH_OT_DATA option"),
J
Jim Meyering 已提交
19150 19151 19152
                 cmd->def->name, optname);
    return found;
}
19153

K
Karel Zak 已提交
19154
static virDomainPtr
J
Jim Meyering 已提交
19155
vshCommandOptDomainBy(vshControl *ctl, const vshCmd *cmd,
19156
                      const char **name, int flag)
19157
{
K
Karel Zak 已提交
19158
    virDomainPtr dom = NULL;
19159
    const char *n = NULL;
K
Karel Zak 已提交
19160
    int id;
J
Jim Meyering 已提交
19161 19162 19163
    const char *optname = "domain";
    if (!cmd_has_option (ctl, cmd, optname))
        return NULL;
19164

19165
    if (vshCommandOptString(cmd, optname, &n) <= 0)
19166 19167
        return NULL;

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

K
Karel Zak 已提交
19171 19172
    if (name)
        *name = n;
19173

K
Karel Zak 已提交
19174
    /* try it by ID */
19175
    if (flag & VSH_BYID) {
19176
        if (virStrToLong_i(n, NULL, 10, &id) == 0 && id >= 0) {
19177 19178
            vshDebug(ctl, VSH_ERR_DEBUG,
                     "%s: <%s> seems like domain ID\n",
K
Karel Zak 已提交
19179 19180 19181
                     cmd->def->name, optname);
            dom = virDomainLookupByID(ctl->conn, id);
        }
19182
    }
K
Karel Zak 已提交
19183
    /* try it by UUID */
19184
    if (dom==NULL && (flag & VSH_BYUUID) && strlen(n)==VIR_UUID_STRING_BUFLEN-1) {
19185
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as domain UUID\n",
19186
                 cmd->def->name, optname);
K
Karel Zak 已提交
19187
        dom = virDomainLookupByUUIDString(ctl->conn, n);
K
Karel Zak 已提交
19188
    }
K
Karel Zak 已提交
19189
    /* try it by NAME */
19190
    if (dom==NULL && (flag & VSH_BYNAME)) {
19191
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as domain NAME\n",
19192
                 cmd->def->name, optname);
K
Karel Zak 已提交
19193
        dom = virDomainLookupByName(ctl->conn, n);
19194
    }
K
Karel Zak 已提交
19195

19196
    if (!dom)
19197
        vshError(ctl, _("failed to get domain '%s'"), n);
19198

K
Karel Zak 已提交
19199 19200 19201
    return dom;
}

19202
static virNetworkPtr
J
Jim Meyering 已提交
19203
vshCommandOptNetworkBy(vshControl *ctl, const vshCmd *cmd,
19204
                       const char **name, int flag)
19205 19206
{
    virNetworkPtr network = NULL;
19207
    const char *n = NULL;
J
Jim Meyering 已提交
19208 19209 19210
    const char *optname = "network";
    if (!cmd_has_option (ctl, cmd, optname))
        return NULL;
19211

19212
    if (vshCommandOptString(cmd, optname, &n) <= 0)
19213 19214
        return NULL;

19215
    vshDebug(ctl, VSH_ERR_INFO, "%s: found option <%s>: %s\n",
19216 19217 19218 19219 19220 19221
             cmd->def->name, optname, n);

    if (name)
        *name = n;

    /* try it by UUID */
E
Eric Blake 已提交
19222
    if ((flag & VSH_BYUUID) && strlen(n) == VIR_UUID_STRING_BUFLEN-1) {
19223
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as network UUID\n",
19224
                 cmd->def->name, optname);
19225 19226 19227 19228
        network = virNetworkLookupByUUIDString(ctl->conn, n);
    }
    /* try it by NAME */
    if (network==NULL && (flag & VSH_BYNAME)) {
19229
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as network NAME\n",
19230 19231 19232 19233 19234
                 cmd->def->name, optname);
        network = virNetworkLookupByName(ctl->conn, n);
    }

    if (!network)
19235
        vshError(ctl, _("failed to get network '%s'"), n);
19236 19237 19238 19239

    return network;
}

19240 19241 19242

static virNWFilterPtr
vshCommandOptNWFilterBy(vshControl *ctl, const vshCmd *cmd,
19243
                        const char **name, int flag)
19244 19245
{
    virNWFilterPtr nwfilter = NULL;
19246
    const char *n = NULL;
19247 19248 19249 19250
    const char *optname = "nwfilter";
    if (!cmd_has_option (ctl, cmd, optname))
        return NULL;

19251
    if (vshCommandOptString(cmd, optname, &n) <= 0)
19252 19253
        return NULL;

19254
    vshDebug(ctl, VSH_ERR_INFO, "%s: found option <%s>: %s\n",
19255 19256 19257 19258 19259 19260
             cmd->def->name, optname, n);

    if (name)
        *name = n;

    /* try it by UUID */
E
Eric Blake 已提交
19261
    if ((flag & VSH_BYUUID) && strlen(n) == VIR_UUID_STRING_BUFLEN-1) {
19262
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as nwfilter UUID\n",
19263 19264 19265 19266 19267
                 cmd->def->name, optname);
        nwfilter = virNWFilterLookupByUUIDString(ctl->conn, n);
    }
    /* try it by NAME */
    if (nwfilter == NULL && (flag & VSH_BYNAME)) {
19268
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as nwfilter NAME\n",
19269 19270 19271 19272 19273 19274 19275 19276 19277 19278
                 cmd->def->name, optname);
        nwfilter = virNWFilterLookupByName(ctl->conn, n);
    }

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

    return nwfilter;
}

19279 19280
static virInterfacePtr
vshCommandOptInterfaceBy(vshControl *ctl, const vshCmd *cmd,
19281
                         const char *optname,
19282
                         const char **name, int flag)
19283 19284
{
    virInterfacePtr iface = NULL;
19285
    const char *n = NULL;
19286 19287 19288

    if (!optname)
       optname = "interface";
19289 19290 19291
    if (!cmd_has_option (ctl, cmd, optname))
        return NULL;

19292
    if (vshCommandOptString(cmd, optname, &n) <= 0)
19293 19294
        return NULL;

19295
    vshDebug(ctl, VSH_ERR_INFO, "%s: found option <%s>: %s\n",
19296 19297 19298 19299 19300 19301
             cmd->def->name, optname, n);

    if (name)
        *name = n;

    /* try it by NAME */
E
Eric Blake 已提交
19302
    if (flag & VSH_BYNAME) {
19303
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as interface NAME\n",
19304 19305 19306 19307
                 cmd->def->name, optname);
        iface = virInterfaceLookupByName(ctl->conn, n);
    }
    /* try it by MAC */
E
Eric Blake 已提交
19308
    if (iface == NULL && (flag & VSH_BYMAC)) {
19309
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as interface MAC\n",
19310 19311 19312 19313 19314
                 cmd->def->name, optname);
        iface = virInterfaceLookupByMACString(ctl->conn, n);
    }

    if (!iface)
19315
        vshError(ctl, _("failed to get interface '%s'"), n);
19316 19317 19318 19319

    return iface;
}

19320
static virStoragePoolPtr
19321
vshCommandOptPoolBy(vshControl *ctl, const vshCmd *cmd, const char *optname,
19322
                    const char **name, int flag)
19323 19324
{
    virStoragePoolPtr pool = NULL;
19325
    const char *n = NULL;
19326

19327
    if (vshCommandOptString(cmd, optname, &n) <= 0)
19328 19329
        return NULL;

19330
    vshDebug(ctl, VSH_ERR_INFO, "%s: found option <%s>: %s\n",
19331 19332 19333 19334 19335 19336
             cmd->def->name, optname, n);

    if (name)
        *name = n;

    /* try it by UUID */
E
Eric Blake 已提交
19337
    if ((flag & VSH_BYUUID) && strlen(n) == VIR_UUID_STRING_BUFLEN-1) {
19338
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as pool UUID\n",
19339
                 cmd->def->name, optname);
19340 19341 19342
        pool = virStoragePoolLookupByUUIDString(ctl->conn, n);
    }
    /* try it by NAME */
19343
    if (pool == NULL && (flag & VSH_BYNAME)) {
19344
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as pool NAME\n",
19345 19346 19347 19348 19349
                 cmd->def->name, optname);
        pool = virStoragePoolLookupByName(ctl->conn, n);
    }

    if (!pool)
19350
        vshError(ctl, _("failed to get pool '%s'"), n);
19351 19352 19353 19354 19355

    return pool;
}

static virStorageVolPtr
19356
vshCommandOptVolBy(vshControl *ctl, const vshCmd *cmd,
19357 19358
                   const char *optname,
                   const char *pooloptname,
19359
                   const char **name, int flag)
19360 19361 19362
{
    virStorageVolPtr vol = NULL;
    virStoragePoolPtr pool = NULL;
19363
    const char *n = NULL, *p = NULL;
19364

19365
    if (vshCommandOptString(cmd, optname, &n) <= 0)
19366 19367
        return NULL;

19368
    if (pooloptname != NULL && vshCommandOptString(cmd, pooloptname, &p) < 0) {
19369
        vshError(ctl, "%s", _("missing option"));
19370
        return NULL;
19371
    }
19372 19373 19374 19375

    if (p)
        pool = vshCommandOptPoolBy(ctl, cmd, pooloptname, name, flag);

19376
    vshDebug(ctl, VSH_ERR_DEBUG, "%s: found option <%s>: %s\n",
19377 19378 19379 19380 19381
             cmd->def->name, optname, n);

    if (name)
        *name = n;

19382
    /* try it by name */
19383
    if (pool && (flag & VSH_BYNAME)) {
19384
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as vol name\n",
19385 19386 19387
                 cmd->def->name, optname);
        vol = virStorageVolLookupByName(pool, n);
    }
19388
    /* try it by key */
19389
    if (vol == NULL && (flag & VSH_BYUUID)) {
19390
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as vol key\n",
19391 19392 19393
                 cmd->def->name, optname);
        vol = virStorageVolLookupByKey(ctl->conn, n);
    }
19394
    /* try it by path */
19395
    if (vol == NULL && (flag & VSH_BYUUID)) {
19396
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as vol path\n",
19397 19398 19399 19400
                 cmd->def->name, optname);
        vol = virStorageVolLookupByPath(ctl->conn, n);
    }

19401 19402 19403 19404
    if (!vol) {
        if (pool)
            vshError(ctl, _("failed to get vol '%s'"), n);
        else
19405 19406
            vshError(ctl, _("failed to get vol '%s', specifying --%s "
                            "might help"), n, pooloptname);
19407
    }
19408 19409 19410 19411 19412 19413 19414

    if (pool)
        virStoragePoolFree(pool);

    return vol;
}

19415
static virSecretPtr
19416
vshCommandOptSecret(vshControl *ctl, const vshCmd *cmd, const char **name)
19417 19418
{
    virSecretPtr secret = NULL;
19419
    const char *n = NULL;
19420 19421 19422 19423 19424
    const char *optname = "secret";

    if (!cmd_has_option (ctl, cmd, optname))
        return NULL;

19425
    if (vshCommandOptString(cmd, optname, &n) <= 0)
19426 19427
        return NULL;

19428 19429
    vshDebug(ctl, VSH_ERR_DEBUG,
             "%s: found option <%s>: %s\n", cmd->def->name, optname, n);
19430 19431 19432 19433 19434 19435 19436

    if (name != NULL)
        *name = n;

    secret = virSecretLookupByUUIDString(ctl->conn, n);

    if (secret == NULL)
19437
        vshError(ctl, _("failed to get secret '%s'"), n);
19438 19439 19440 19441

    return secret;
}

K
Karel Zak 已提交
19442 19443 19444
/*
 * Executes command(s) and returns return code from last command
 */
E
Eric Blake 已提交
19445
static bool
19446
vshCommandRun(vshControl *ctl, const vshCmd *cmd)
19447
{
E
Eric Blake 已提交
19448
    bool ret = true;
19449 19450

    while (cmd) {
K
Karel Zak 已提交
19451
        struct timeval before, after;
19452
        bool enable_timing = ctl->timing;
19453

19454 19455
        if ((ctl->conn == NULL || disconnected) &&
            !(cmd->def->flags & VSH_CMD_FLAG_NOCONNECT))
19456 19457
            vshReconnect(ctl);

19458
        if (enable_timing)
K
Karel Zak 已提交
19459
            GETTIMEOFDAY(&before);
19460

K
Karel Zak 已提交
19461 19462
        ret = cmd->def->handler(ctl, cmd);

19463
        if (enable_timing)
K
Karel Zak 已提交
19464
            GETTIMEOFDAY(&after);
19465

19466 19467 19468 19469 19470 19471 19472 19473 19474 19475
        /* try to automatically catch disconnections */
        if (!ret &&
            ((last_error != NULL) &&
             (((last_error->code == VIR_ERR_SYSTEM_ERROR) &&
               (last_error->domain == VIR_FROM_REMOTE)) ||
              (last_error->code == VIR_ERR_RPC) ||
              (last_error->code == VIR_ERR_NO_CONNECT) ||
              (last_error->code == VIR_ERR_INVALID_CONN))))
            disconnected++;

19476
        if (!ret)
J
John Levon 已提交
19477 19478
            virshReportError(ctl);

19479
        if (!ret && disconnected != 0)
19480 19481
            vshReconnect(ctl);

19482
        if (STREQ(cmd->def->name, "quit"))        /* hack ... */
K
Karel Zak 已提交
19483 19484
            return ret;

19485
        if (enable_timing)
19486
            vshPrint(ctl, _("\n(Time: %.3f ms)\n\n"),
19487 19488
                     DIFF_MSEC(&after, &before));
        else
K
Karel Zak 已提交
19489
            vshPrintExtra(ctl, "\n");
K
Karel Zak 已提交
19490 19491 19492 19493 19494 19495
        cmd = cmd->next;
    }
    return ret;
}

/* ---------------
19496
 * Command parsing
K
Karel Zak 已提交
19497 19498 19499
 * ---------------
 */

19500 19501 19502 19503 19504 19505 19506 19507 19508 19509
typedef enum {
    VSH_TK_ERROR, /* Failed to parse a token */
    VSH_TK_ARG, /* Arbitrary argument, might be option or empty */
    VSH_TK_SUBCMD_END, /* Separation between commands */
    VSH_TK_END /* No more commands */
} vshCommandToken;

typedef struct __vshCommandParser {
    vshCommandToken (*getNextArg)(vshControl *, struct __vshCommandParser *,
                                  char **);
L
Lai Jiangshan 已提交
19510
    /* vshCommandStringGetArg() */
19511
    char *pos;
L
Lai Jiangshan 已提交
19512 19513 19514
    /* vshCommandArgvGetArg() */
    char **arg_pos;
    char **arg_end;
19515 19516
} vshCommandParser;

E
Eric Blake 已提交
19517
static bool
19518
vshCommandParse(vshControl *ctl, vshCommandParser *parser)
19519
{
K
Karel Zak 已提交
19520 19521 19522
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
19523

K
Karel Zak 已提交
19524 19525 19526 19527
    if (ctl->cmd) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
19528

19529
    while (1) {
K
Karel Zak 已提交
19530
        vshCmdOpt *last = NULL;
19531
        const vshCmdDef *cmd = NULL;
19532
        vshCommandToken tk;
L
Lai Jiangshan 已提交
19533
        bool data_only = false;
19534 19535 19536
        uint32_t opts_need_arg = 0;
        uint32_t opts_required = 0;
        uint32_t opts_seen = 0;
19537

K
Karel Zak 已提交
19538
        first = NULL;
19539

19540
        while (1) {
19541
            const vshCmdOptDef *opt = NULL;
19542

K
Karel Zak 已提交
19543
            tkdata = NULL;
19544
            tk = parser->getNextArg(ctl, parser, &tkdata);
19545 19546

            if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
19547
                goto syntaxError;
H
Hu Tao 已提交
19548 19549
            if (tk != VSH_TK_ARG) {
                VIR_FREE(tkdata);
19550
                break;
H
Hu Tao 已提交
19551
            }
19552 19553

            if (cmd == NULL) {
K
Karel Zak 已提交
19554 19555
                /* first token must be command name */
                if (!(cmd = vshCmddefSearch(tkdata))) {
19556
                    vshError(ctl, _("unknown command: '%s'"), tkdata);
19557
                    goto syntaxError;   /* ... or ignore this command only? */
K
Karel Zak 已提交
19558
                }
19559 19560 19561 19562 19563 19564 19565
                if (vshCmddefOptParse(cmd, &opts_need_arg,
                                      &opts_required) < 0) {
                    vshError(ctl,
                             _("internal error: bad options in command: '%s'"),
                             tkdata);
                    goto syntaxError;
                }
19566
                VIR_FREE(tkdata);
L
Lai Jiangshan 已提交
19567 19568 19569 19570
            } else if (data_only) {
                goto get_data;
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       c_isalnum(tkdata[2])) {
19571
                char *optstr = strchr(tkdata + 2, '=');
19572 19573
                int opt_index;

19574 19575 19576 19577
                if (optstr) {
                    *optstr = '\0'; /* convert the '=' to '\0' */
                    optstr = vshStrdup(ctl, optstr + 1);
                }
19578
                if (!(opt = vshCmddefGetOption(ctl, cmd, tkdata + 2,
19579
                                               &opts_seen, &opt_index))) {
19580
                    VIR_FREE(optstr);
K
Karel Zak 已提交
19581 19582
                    goto syntaxError;
                }
19583
                VIR_FREE(tkdata);
K
Karel Zak 已提交
19584 19585 19586

                if (opt->type != VSH_OT_BOOL) {
                    /* option data */
19587 19588 19589
                    if (optstr)
                        tkdata = optstr;
                    else
19590
                        tk = parser->getNextArg(ctl, parser, &tkdata);
19591
                    if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
19592
                        goto syntaxError;
19593
                    if (tk != VSH_TK_ARG) {
19594
                        vshError(ctl,
19595
                                 _("expected syntax: --%s <%s>"),
19596 19597
                                 opt->name,
                                 opt->type ==
19598
                                 VSH_OT_INT ? _("number") : _("string"));
K
Karel Zak 已提交
19599 19600
                        goto syntaxError;
                    }
19601 19602
                    if (opt->type != VSH_OT_ARGV)
                        opts_need_arg &= ~(1 << opt_index);
19603 19604 19605 19606 19607 19608 19609 19610
                } else {
                    tkdata = NULL;
                    if (optstr) {
                        vshError(ctl, _("invalid '=' after option --%s"),
                                opt->name);
                        VIR_FREE(optstr);
                        goto syntaxError;
                    }
K
Karel Zak 已提交
19611
                }
L
Lai Jiangshan 已提交
19612 19613 19614 19615
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       tkdata[2] == '\0') {
                data_only = true;
                continue;
19616
            } else {
L
Lai Jiangshan 已提交
19617
get_data:
19618 19619
                if (!(opt = vshCmddefGetData(cmd, &opts_need_arg,
                                             &opts_seen))) {
19620
                    vshError(ctl, _("unexpected data '%s'"), tkdata);
K
Karel Zak 已提交
19621 19622 19623 19624 19625
                    goto syntaxError;
                }
            }
            if (opt) {
                /* save option */
19626
                vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));
19627

K
Karel Zak 已提交
19628 19629 19630 19631
                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;
19632

K
Karel Zak 已提交
19633 19634 19635 19636 19637
                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;
19638

19639
                vshDebug(ctl, VSH_ERR_INFO, "%s: %s(%s): %s\n",
19640 19641
                         cmd->name,
                         opt->name,
19642 19643
                         opt->type != VSH_OT_BOOL ? _("optdata") : _("bool"),
                         opt->type != VSH_OT_BOOL ? arg->data : _("(none)"));
K
Karel Zak 已提交
19644 19645
            }
        }
19646

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

K
Karel Zak 已提交
19651 19652 19653 19654
            c->opts = first;
            c->def = cmd;
            c->next = NULL;

19655
            if (vshCommandCheckOpts(ctl, c, opts_required, opts_seen) < 0) {
19656
                VIR_FREE(c);
19657
                goto syntaxError;
19658
            }
19659

K
Karel Zak 已提交
19660 19661 19662 19663 19664 19665
            if (!ctl->cmd)
                ctl->cmd = c;
            if (clast)
                clast->next = c;
            clast = c;
        }
19666 19667 19668

        if (tk == VSH_TK_END)
            break;
K
Karel Zak 已提交
19669
    }
19670

E
Eric Blake 已提交
19671
    return true;
K
Karel Zak 已提交
19672

19673
 syntaxError:
19674
    if (ctl->cmd) {
K
Karel Zak 已提交
19675
        vshCommandFree(ctl->cmd);
19676 19677
        ctl->cmd = NULL;
    }
K
Karel Zak 已提交
19678 19679
    if (first)
        vshCommandOptFree(first);
19680
    VIR_FREE(tkdata);
E
Eric Blake 已提交
19681
    return false;
K
Karel Zak 已提交
19682 19683
}

19684 19685 19686 19687 19688 19689 19690 19691 19692 19693 19694 19695 19696 19697 19698 19699 19700 19701
/* --------------------
 * Command argv parsing
 * --------------------
 */

static vshCommandToken ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(3)
vshCommandArgvGetArg(vshControl *ctl, vshCommandParser *parser, char **res)
{
    if (parser->arg_pos == parser->arg_end) {
        *res = NULL;
        return VSH_TK_END;
    }

    *res = vshStrdup(ctl, *parser->arg_pos);
    parser->arg_pos++;
    return VSH_TK_ARG;
}

E
Eric Blake 已提交
19702 19703
static bool
vshCommandArgvParse(vshControl *ctl, int nargs, char **argv)
19704 19705 19706 19707
{
    vshCommandParser parser;

    if (nargs <= 0)
E
Eric Blake 已提交
19708
        return false;
19709 19710 19711 19712 19713 19714 19715 19716 19717 19718 19719 19720 19721 19722 19723 19724 19725 19726 19727 19728 19729 19730 19731 19732 19733 19734 19735 19736 19737 19738 19739 19740 19741 19742 19743 19744 19745 19746 19747 19748 19749 19750 19751 19752 19753 19754 19755 19756 19757 19758 19759 19760 19761 19762 19763 19764 19765 19766 19767 19768 19769 19770 19771 19772 19773 19774 19775 19776 19777 19778 19779 19780

    parser.arg_pos = argv;
    parser.arg_end = argv + nargs;
    parser.getNextArg = vshCommandArgvGetArg;
    return vshCommandParse(ctl, &parser);
}

/* ----------------------
 * Command string parsing
 * ----------------------
 */

static vshCommandToken ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(3)
vshCommandStringGetArg(vshControl *ctl, vshCommandParser *parser, char **res)
{
    bool single_quote = false;
    bool double_quote = false;
    int sz = 0;
    char *p = parser->pos;
    char *q = vshStrdup(ctl, p);

    *res = q;

    while (*p && (*p == ' ' || *p == '\t'))
        p++;

    if (*p == '\0')
        return VSH_TK_END;
    if (*p == ';') {
        parser->pos = ++p;             /* = \0 or begin of next command */
        return VSH_TK_SUBCMD_END;
    }

    while (*p) {
        /* end of token is blank space or ';' */
        if (!double_quote && !single_quote &&
            (*p == ' ' || *p == '\t' || *p == ';'))
            break;

        if (!double_quote && *p == '\'') { /* single quote */
            single_quote = !single_quote;
            p++;
            continue;
        } else if (!single_quote && *p == '\\') { /* escape */
            /*
             * The same as the bash, a \ in "" is an escaper,
             * but a \ in '' is not an escaper.
             */
            p++;
            if (*p == '\0') {
                vshError(ctl, "%s", _("dangling \\"));
                return VSH_TK_ERROR;
            }
        } else if (!single_quote && *p == '"') { /* double quote */
            double_quote = !double_quote;
            p++;
            continue;
        }

        *q++ = *p++;
        sz++;
    }
    if (double_quote) {
        vshError(ctl, "%s", _("missing \""));
        return VSH_TK_ERROR;
    }

    *q = '\0';
    parser->pos = p;
    return VSH_TK_ARG;
}

E
Eric Blake 已提交
19781 19782
static bool
vshCommandStringParse(vshControl *ctl, char *cmdstr)
19783 19784 19785 19786
{
    vshCommandParser parser;

    if (cmdstr == NULL || *cmdstr == '\0')
E
Eric Blake 已提交
19787
        return false;
19788 19789 19790 19791 19792 19793

    parser.pos = cmdstr;
    parser.getNextArg = vshCommandStringGetArg;
    return vshCommandParse(ctl, &parser);
}

K
Karel Zak 已提交
19794
/* ---------------
19795
 * Misc utils
K
Karel Zak 已提交
19796 19797
 * ---------------
 */
19798 19799 19800 19801 19802 19803 19804 19805 19806 19807 19808 19809 19810 19811 19812 19813 19814 19815 19816 19817 19818 19819 19820 19821 19822 19823 19824 19825
static int
vshDomainState(vshControl *ctl, virDomainPtr dom, int *reason)
{
    virDomainInfo info;

    if (reason)
        *reason = -1;

    if (!ctl->useGetInfo) {
        int state;
        if (virDomainGetState(dom, &state, reason, 0) < 0) {
            virErrorPtr err = virGetLastError();
            if (err && err->code == VIR_ERR_NO_SUPPORT)
                ctl->useGetInfo = true;
            else
                return -1;
        } else {
            return state;
        }
    }

    /* fall back to virDomainGetInfo if virDomainGetState is not supported */
    if (virDomainGetInfo(dom, &info) < 0)
        return -1;
    else
        return info.state;
}

K
Karel Zak 已提交
19826
static const char *
19827 19828
vshDomainStateToString(int state)
{
19829 19830
    /* Can't use virDomainStateTypeToString, because we want to mark
     * strings for translation.  */
19831
    switch ((virDomainState) state) {
19832
    case VIR_DOMAIN_RUNNING:
19833
        return N_("running");
19834
    case VIR_DOMAIN_BLOCKED:
19835
        return N_("idle");
19836
    case VIR_DOMAIN_PAUSED:
19837
        return N_("paused");
19838
    case VIR_DOMAIN_SHUTDOWN:
19839
        return N_("in shutdown");
19840
    case VIR_DOMAIN_SHUTOFF:
19841
        return N_("shut off");
19842
    case VIR_DOMAIN_CRASHED:
19843
        return N_("crashed");
O
Osier Yang 已提交
19844 19845
    case VIR_DOMAIN_PMSUSPENDED:
        return N_("pmsuspended");
19846
    case VIR_DOMAIN_NOSTATE:
19847
    default:
19848
        ;/*FALLTHROUGH*/
K
Karel Zak 已提交
19849
    }
19850
    return N_("no state");  /* = dom0 state */
K
Karel Zak 已提交
19851 19852
}

19853 19854 19855 19856 19857 19858 19859
static const char *
vshDomainStateReasonToString(int state, int reason)
{
    switch ((virDomainState) state) {
    case VIR_DOMAIN_NOSTATE:
        switch ((virDomainNostateReason) reason) {
        case VIR_DOMAIN_NOSTATE_UNKNOWN:
19860
        case VIR_DOMAIN_NOSTATE_LAST:
19861 19862 19863 19864 19865 19866 19867 19868 19869 19870 19871 19872 19873 19874 19875 19876 19877 19878 19879 19880
            ;
        }
        break;

    case VIR_DOMAIN_RUNNING:
        switch ((virDomainRunningReason) reason) {
        case VIR_DOMAIN_RUNNING_BOOTED:
            return N_("booted");
        case VIR_DOMAIN_RUNNING_MIGRATED:
            return N_("migrated");
        case VIR_DOMAIN_RUNNING_RESTORED:
            return N_("restored");
        case VIR_DOMAIN_RUNNING_FROM_SNAPSHOT:
            return N_("from snapshot");
        case VIR_DOMAIN_RUNNING_UNPAUSED:
            return N_("unpaused");
        case VIR_DOMAIN_RUNNING_MIGRATION_CANCELED:
            return N_("migration canceled");
        case VIR_DOMAIN_RUNNING_SAVE_CANCELED:
            return N_("save canceled");
19881 19882
        case VIR_DOMAIN_RUNNING_WAKEUP:
            return N_("event wakeup");
19883
        case VIR_DOMAIN_RUNNING_UNKNOWN:
19884
        case VIR_DOMAIN_RUNNING_LAST:
19885 19886 19887 19888 19889 19890 19891
            ;
        }
        break;

    case VIR_DOMAIN_BLOCKED:
        switch ((virDomainBlockedReason) reason) {
        case VIR_DOMAIN_BLOCKED_UNKNOWN:
19892
        case VIR_DOMAIN_BLOCKED_LAST:
19893 19894 19895 19896 19897 19898 19899 19900 19901 19902 19903 19904 19905 19906 19907 19908 19909 19910 19911 19912
            ;
        }
        break;

    case VIR_DOMAIN_PAUSED:
        switch ((virDomainPausedReason) reason) {
        case VIR_DOMAIN_PAUSED_USER:
            return N_("user");
        case VIR_DOMAIN_PAUSED_MIGRATION:
            return N_("migrating");
        case VIR_DOMAIN_PAUSED_SAVE:
            return N_("saving");
        case VIR_DOMAIN_PAUSED_DUMP:
            return N_("dumping");
        case VIR_DOMAIN_PAUSED_IOERROR:
            return N_("I/O error");
        case VIR_DOMAIN_PAUSED_WATCHDOG:
            return N_("watchdog");
        case VIR_DOMAIN_PAUSED_FROM_SNAPSHOT:
            return N_("from snapshot");
19913 19914
        case VIR_DOMAIN_PAUSED_SHUTTING_DOWN:
            return N_("shutting down");
19915
        case VIR_DOMAIN_PAUSED_UNKNOWN:
19916
        case VIR_DOMAIN_PAUSED_LAST:
19917 19918 19919 19920 19921 19922 19923 19924 19925
            ;
        }
        break;

    case VIR_DOMAIN_SHUTDOWN:
        switch ((virDomainShutdownReason) reason) {
        case VIR_DOMAIN_SHUTDOWN_USER:
            return N_("user");
        case VIR_DOMAIN_SHUTDOWN_UNKNOWN:
19926
        case VIR_DOMAIN_SHUTDOWN_LAST:
19927 19928 19929 19930 19931 19932 19933 19934 19935 19936 19937 19938 19939 19940 19941 19942 19943 19944 19945 19946 19947
            ;
        }
        break;

    case VIR_DOMAIN_SHUTOFF:
        switch ((virDomainShutoffReason) reason) {
        case VIR_DOMAIN_SHUTOFF_SHUTDOWN:
            return N_("shutdown");
        case VIR_DOMAIN_SHUTOFF_DESTROYED:
            return N_("destroyed");
        case VIR_DOMAIN_SHUTOFF_CRASHED:
            return N_("crashed");
        case VIR_DOMAIN_SHUTOFF_MIGRATED:
            return N_("migrated");
        case VIR_DOMAIN_SHUTOFF_SAVED:
            return N_("saved");
        case VIR_DOMAIN_SHUTOFF_FAILED:
            return N_("failed");
        case VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT:
            return N_("from snapshot");
        case VIR_DOMAIN_SHUTOFF_UNKNOWN:
19948
        case VIR_DOMAIN_SHUTOFF_LAST:
19949 19950 19951 19952 19953 19954 19955
            ;
        }
        break;

    case VIR_DOMAIN_CRASHED:
        switch ((virDomainCrashedReason) reason) {
        case VIR_DOMAIN_CRASHED_UNKNOWN:
19956
        case VIR_DOMAIN_CRASHED_LAST:
19957 19958 19959
            ;
        }
        break;
19960

O
Osier Yang 已提交
19961 19962 19963 19964 19965 19966 19967 19968
    case VIR_DOMAIN_PMSUSPENDED:
        switch ((virDomainPMSuspendedReason) reason) {
        case VIR_DOMAIN_PMSUSPENDED_UNKNOWN:
        case VIR_DOMAIN_PMSUSPENDED_LAST:
            ;
        }
        break;

19969
    case VIR_DOMAIN_LAST:
19970
        ;
19971 19972 19973 19974 19975
    }

    return N_("unknown");
}

19976 19977 19978 19979 19980 19981 19982 19983 19984 19985 19986 19987 19988 19989 19990 19991 19992 19993 19994 19995 19996 19997 19998 19999 20000 20001 20002 20003 20004 20005 20006 20007 20008 20009 20010 20011 20012 20013 20014 20015 20016 20017 20018 20019 20020 20021 20022 20023 20024 20025 20026 20027 20028 20029 20030 20031 20032 20033 20034
/* extract description or title from domain xml */
static char *
vshGetDomainDescription(vshControl *ctl, virDomainPtr dom, bool title,
                        unsigned int flags)
{
    char *desc = NULL;
    char *domxml = NULL;
    virErrorPtr err = NULL;
    xmlDocPtr doc = NULL;
    xmlXPathContextPtr ctxt = NULL;
    int type;

    if (title)
        type = VIR_DOMAIN_METADATA_TITLE;
    else
        type = VIR_DOMAIN_METADATA_DESCRIPTION;

    if ((desc = virDomainGetMetadata(dom, type, NULL, flags))) {
        return desc;
    } else {
        err = virGetLastError();

        if (err && err->code == VIR_ERR_NO_DOMAIN_METADATA) {
            desc = vshStrdup(ctl, "");
            virResetLastError();
            return desc;
        }

        if (err && err->code != VIR_ERR_NO_SUPPORT)
            return desc;
    }

    /* fall back to xml */
    /* get domain's xml description and extract the title/description */
    if (!(domxml = virDomainGetXMLDesc(dom, flags))) {
        vshError(ctl, "%s", _("Failed to retrieve domain XML"));
        goto cleanup;
    }
    doc = virXMLParseStringCtxt(domxml, _("(domain_definition)"), &ctxt);
    if (!doc) {
        vshError(ctl, "%s", _("Couldn't parse domain XML"));
        goto cleanup;
    }
    if (title)
        desc = virXPathString("string(./title[1])", ctxt);
    else
        desc = virXPathString("string(./description[1])", ctxt);

    if (!desc)
        desc = vshStrdup(ctl, "");

cleanup:
    VIR_FREE(domxml);
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(doc);

    return desc;
}

20035 20036
/* Return a non-NULL string representation of a typed parameter; exit
 * if we are out of memory.  */
20037 20038 20039 20040 20041 20042 20043 20044 20045 20046 20047 20048 20049 20050 20051 20052 20053 20054 20055 20056 20057 20058 20059 20060 20061 20062 20063 20064 20065 20066 20067
static char *
vshGetTypedParamValue(vshControl *ctl, virTypedParameterPtr item)
{
    int ret = 0;
    char *str = NULL;

    switch(item->type) {
    case VIR_TYPED_PARAM_INT:
        ret = virAsprintf(&str, "%d", item->value.i);
        break;

    case VIR_TYPED_PARAM_UINT:
        ret = virAsprintf(&str, "%u", item->value.ui);
        break;

    case VIR_TYPED_PARAM_LLONG:
        ret = virAsprintf(&str, "%lld", item->value.l);
        break;

    case VIR_TYPED_PARAM_ULLONG:
        ret = virAsprintf(&str, "%llu", item->value.ul);
        break;

    case VIR_TYPED_PARAM_DOUBLE:
        ret = virAsprintf(&str, "%f", item->value.d);
        break;

    case VIR_TYPED_PARAM_BOOLEAN:
        ret = virAsprintf(&str, "%s", item->value.b ? _("yes") : _("no"));
        break;

20068 20069 20070 20071
    case VIR_TYPED_PARAM_STRING:
        str = vshStrdup(ctl, item->value.s);
        break;

20072
    default:
20073
        vshError(ctl, _("unimplemented parameter type %d"), item->type);
20074 20075
    }

20076
    if (ret < 0) {
20077
        vshError(ctl, "%s", _("Out of memory"));
20078 20079
        exit(EXIT_FAILURE);
    }
20080 20081 20082 20083 20084 20085 20086 20087 20088 20089 20090 20091 20092 20093 20094 20095 20096 20097 20098 20099 20100 20101 20102
    return str;
}

static virTypedParameterPtr
vshFindTypedParamByName(const char *name, virTypedParameterPtr list, int count)
{
    int i = count;
    virTypedParameterPtr found = list;

    if (!list || !name)
        return NULL;

    while (i-- > 0) {
        if (STREQ(name, found->field))
            return found;

        found++; /* go to next struct in array */
    }

    /* not found */
    return NULL;
}

20103 20104 20105 20106 20107 20108 20109 20110 20111 20112 20113 20114
static const char *
vshDomainControlStateToString(int state)
{
    switch ((virDomainControlState) state) {
    case VIR_DOMAIN_CONTROL_OK:
        return N_("ok");
    case VIR_DOMAIN_CONTROL_JOB:
        return N_("background job");
    case VIR_DOMAIN_CONTROL_OCCUPIED:
        return N_("occupied");
    case VIR_DOMAIN_CONTROL_ERROR:
        return N_("error");
20115 20116
    default:
        ;
20117 20118 20119 20120 20121
    }

    return N_("unknown");
}

20122 20123 20124 20125
static const char *
vshDomainVcpuStateToString(int state)
{
    switch (state) {
20126
    case VIR_VCPU_OFFLINE:
20127
        return N_("offline");
20128
    case VIR_VCPU_BLOCKED:
20129
        return N_("idle");
20130
    case VIR_VCPU_RUNNING:
20131
        return N_("running");
20132
    default:
20133
        ;/*FALLTHROUGH*/
20134
    }
20135
    return N_("no state");
20136 20137
}

E
Eric Blake 已提交
20138
static bool
20139
vshConnectionUsability(vshControl *ctl, virConnectPtr conn)
20140
{
20141 20142
    /* TODO: use something like virConnectionState() to
     *       check usability of the connection
K
Karel Zak 已提交
20143 20144
     */
    if (!conn) {
20145
        vshError(ctl, "%s", _("no valid connection"));
E
Eric Blake 已提交
20146
        return false;
K
Karel Zak 已提交
20147
    }
E
Eric Blake 已提交
20148
    return true;
K
Karel Zak 已提交
20149 20150
}

K
Karel Zak 已提交
20151
static void
20152
vshDebug(vshControl *ctl, int level, const char *format, ...)
20153
{
K
Karel Zak 已提交
20154
    va_list ap;
20155
    char *str;
K
Karel Zak 已提交
20156

20157 20158 20159 20160 20161 20162 20163
    /* Aligning log levels to that of libvirt.
     * Traces with levels >=  user-specified-level
     * gets logged into file
     */
    if (level < ctl->debug)
        return;

20164
    va_start(ap, format);
20165
    vshOutputLogFile(ctl, level, format, ap);
20166 20167
    va_end(ap);

K
Karel Zak 已提交
20168
    va_start(ap, format);
20169 20170 20171 20172 20173
    if (virVasprintf(&str, format, ap) < 0) {
        /* Skip debug messages on low memory */
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
20174
    va_end(ap);
20175 20176
    fputs(str, stdout);
    VIR_FREE(str);
K
Karel Zak 已提交
20177 20178 20179
}

static void
20180
vshPrintExtra(vshControl *ctl, const char *format, ...)
20181
{
K
Karel Zak 已提交
20182
    va_list ap;
20183
    char *str;
20184

20185
    if (ctl && ctl->quiet)
K
Karel Zak 已提交
20186
        return;
20187

K
Karel Zak 已提交
20188
    va_start(ap, format);
20189 20190 20191 20192 20193
    if (virVasprintf(&str, format, ap) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
20194
    va_end(ap);
20195
    fputs(str, stdout);
20196
    VIR_FREE(str);
K
Karel Zak 已提交
20197 20198
}

K
Karel Zak 已提交
20199

K
Karel Zak 已提交
20200
static void
20201
vshError(vshControl *ctl, const char *format, ...)
20202
{
K
Karel Zak 已提交
20203
    va_list ap;
20204
    char *str;
20205

20206 20207 20208 20209 20210
    if (ctl != NULL) {
        va_start(ap, format);
        vshOutputLogFile(ctl, VSH_ERR_ERROR, format, ap);
        va_end(ap);
    }
20211

20212 20213 20214 20215
    /* Most output is to stdout, but if someone ran virsh 2>&1, then
     * printing to stderr will not interleave correctly with stdout
     * unless we flush between every transition between streams.  */
    fflush(stdout);
20216
    fputs(_("error: "), stderr);
20217

K
Karel Zak 已提交
20218
    va_start(ap, format);
20219 20220 20221
    /* We can't recursively call vshError on an OOM situation, so ignore
       failure here. */
    ignore_value(virVasprintf(&str, format, ap));
K
Karel Zak 已提交
20222 20223
    va_end(ap);

20224
    fprintf(stderr, "%s\n", NULLSTR(str));
20225
    fflush(stderr);
20226
    VIR_FREE(str);
K
Karel Zak 已提交
20227 20228
}

20229

J
Jiri Denemark 已提交
20230 20231 20232 20233 20234
static void
vshEventLoop(void *opaque)
{
    vshControl *ctl = opaque;

20235 20236 20237 20238 20239 20240 20241 20242 20243 20244
    while (1) {
        bool quit;
        virMutexLock(&ctl->lock);
        quit = ctl->quit;
        virMutexUnlock(&ctl->lock);

        if (quit)
            break;

        if (virEventRunDefaultImpl() < 0)
J
Jiri Denemark 已提交
20245 20246 20247 20248 20249
            virshReportError(ctl);
    }
}


K
Karel Zak 已提交
20250
/*
20251
 * Initialize connection.
K
Karel Zak 已提交
20252
 */
E
Eric Blake 已提交
20253
static bool
20254
vshInit(vshControl *ctl)
20255
{
20256 20257
    char *debugEnv;

K
Karel Zak 已提交
20258
    if (ctl->conn)
E
Eric Blake 已提交
20259
        return false;
K
Karel Zak 已提交
20260

J
Jiri Denemark 已提交
20261
    if (ctl->debug == VSH_DEBUG_DEFAULT) {
20262 20263 20264
        /* log level not set from commandline, check env variable */
        debugEnv = getenv("VIRSH_DEBUG");
        if (debugEnv) {
J
Jiri Denemark 已提交
20265 20266 20267
            int debug;
            if (virStrToLong_i(debugEnv, NULL, 10, &debug) < 0 ||
                debug < VSH_ERR_DEBUG || debug > VSH_ERR_ERROR) {
20268 20269
                vshError(ctl, "%s",
                         _("VIRSH_DEBUG not set with a valid numeric value"));
J
Jiri Denemark 已提交
20270 20271
            } else {
                ctl->debug = debug;
20272 20273 20274 20275 20276 20277 20278 20279 20280 20281 20282 20283
            }
        }
    }

    if (ctl->logfile == NULL) {
        /* log file not set from cmdline */
        debugEnv = getenv("VIRSH_LOG_FILE");
        if (debugEnv && *debugEnv) {
            ctl->logfile = vshStrdup(ctl, debugEnv);
        }
    }

20284 20285
    vshOpenLogFile(ctl);

20286 20287
    /* set up the library error handler */
    virSetErrorFunc(NULL, virshErrorHandler);
20288

20289 20290 20291
    /* set up the signals handlers to catch disconnections */
    vshSetupSignals();

20292
    if (virEventRegisterDefaultImpl() < 0)
E
Eric Blake 已提交
20293
        return false;
20294

J
Jiri Denemark 已提交
20295 20296 20297 20298
    if (virThreadCreate(&ctl->eventLoop, true, vshEventLoop, ctl) < 0)
        return false;
    ctl->eventLoopStarted = true;

20299 20300 20301 20302
    if (ctl->name) {
        ctl->conn = virConnectOpenAuth(ctl->name,
                                       virConnectAuthPtrDefault,
                                       ctl->readonly ? VIR_CONNECT_RO : 0);
20303

20304 20305 20306 20307 20308 20309 20310 20311 20312 20313 20314
        /* Connecting to a named connection must succeed, but we delay
         * connecting to the default connection until we need it
         * (since the first command might be 'connect' which allows a
         * non-default connection, or might be 'help' which needs no
         * connection).
         */
        if (!ctl->conn) {
            virshReportError(ctl);
            vshError(ctl, "%s", _("failed to connect to the hypervisor"));
            return false;
        }
20315
    }
K
Karel Zak 已提交
20316

E
Eric Blake 已提交
20317
    return true;
K
Karel Zak 已提交
20318 20319
}

20320 20321
#define LOGFILE_FLAGS (O_WRONLY | O_APPEND | O_CREAT | O_SYNC)

20322 20323 20324 20325 20326 20327 20328 20329 20330 20331 20332 20333 20334 20335 20336 20337 20338 20339 20340
/**
 * 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:
20341
                vshError(ctl, "%s",
J
Jim Meyering 已提交
20342
                         _("failed to get the log file information"));
20343
                exit(EXIT_FAILURE);
20344 20345 20346
        }
    } else {
        if (!S_ISREG(st.st_mode)) {
20347 20348
            vshError(ctl, "%s", _("the log path is not a file"));
            exit(EXIT_FAILURE);
20349 20350 20351 20352
        }
    }

    /* log file open */
20353
    if ((ctl->log_fd = open(ctl->logfile, LOGFILE_FLAGS, FILE_MODE)) < 0) {
20354
        vshError(ctl, "%s",
J
Jim Meyering 已提交
20355
                 _("failed to open the log file. check the log file path"));
20356
        exit(EXIT_FAILURE);
20357 20358 20359 20360 20361 20362 20363 20364 20365
    }
}

/**
 * vshOutputLogFile:
 *
 * Outputting an error to log file.
 */
static void
20366 20367
vshOutputLogFile(vshControl *ctl, int log_level, const char *msg_format,
                 va_list ap)
20368
{
20369 20370 20371
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char *str;
    size_t len;
20372 20373 20374 20375 20376 20377 20378 20379 20380 20381 20382 20383 20384 20385
    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);
20386
    virBufferAsprintf(&buf, "[%d.%02d.%02d %02d:%02d:%02d %s %d] ",
20387 20388 20389 20390 20391 20392
                      (1900 + stTm->tm_year),
                      (1 + stTm->tm_mon),
                      stTm->tm_mday,
                      stTm->tm_hour,
                      stTm->tm_min,
                      stTm->tm_sec,
20393 20394
                      SIGN_NAME,
                      (int) getpid());
20395 20396 20397 20398 20399 20400 20401 20402 20403 20404 20405 20406 20407 20408 20409 20410 20411 20412 20413 20414
    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;
    }
20415 20416 20417
    virBufferAsprintf(&buf, "%s ", lvl);
    virBufferVasprintf(&buf, msg_format, ap);
    virBufferAddChar(&buf, '\n');
20418

20419 20420
    if (virBufferError(&buf))
        goto error;
20421

20422 20423 20424 20425 20426
    str = virBufferContentAndReset(&buf);
    len = strlen(str);
    if (len > 1 && str[len - 2] == '\n') {
        str[len - 1] = '\0';
        len--;
20427
    }
20428

20429 20430 20431 20432 20433 20434 20435 20436 20437 20438 20439
    /* write log */
    if (safewrite(ctl->log_fd, str, len) < 0)
        goto error;

    return;

error:
    vshCloseLogFile(ctl);
    vshError(ctl, "%s", _("failed to write the log file"));
    virBufferFreeAndReset(&buf);
    VIR_FREE(str);
20440 20441 20442 20443 20444 20445 20446 20447 20448 20449 20450
}

/**
 * vshCloseLogFile:
 *
 * Close log file.
 */
static void
vshCloseLogFile(vshControl *ctl)
{
    /* log file close */
20451 20452 20453
    if (VIR_CLOSE(ctl->log_fd) < 0) {
        vshError(ctl, _("%s: failed to write log file: %s"),
                 ctl->logfile ? ctl->logfile : "?", strerror (errno));
20454 20455 20456
    }

    if (ctl->logfile) {
20457
        VIR_FREE(ctl->logfile);
20458 20459 20460 20461
        ctl->logfile = NULL;
    }
}

20462
#ifdef USE_READLINE
20463

K
Karel Zak 已提交
20464 20465 20466 20467 20468
/* -----------------
 * Readline stuff
 * -----------------
 */

20469
/*
K
Karel Zak 已提交
20470 20471
 * Generator function for command completion.  STATE lets us
 * know whether to start from scratch; without any state
20472
 * (i.e. STATE == 0), then we start at the top of the list.
K
Karel Zak 已提交
20473 20474
 */
static char *
20475 20476
vshReadlineCommandGenerator(const char *text, int state)
{
20477
    static int grp_list_index, cmd_list_index, len;
K
Karel Zak 已提交
20478
    const char *name;
20479 20480
    const vshCmdGrp *grp;
    const vshCmdDef *cmds;
K
Karel Zak 已提交
20481 20482

    if (!state) {
20483 20484
        grp_list_index = 0;
        cmd_list_index = 0;
20485
        len = strlen(text);
K
Karel Zak 已提交
20486 20487
    }

20488 20489
    grp = cmdGroups;

K
Karel Zak 已提交
20490
    /* Return the next name which partially matches from the
20491
     * command list.
K
Karel Zak 已提交
20492
     */
20493 20494 20495 20496 20497 20498 20499 20500 20501 20502 20503 20504 20505 20506
    while (grp[grp_list_index].name) {
        cmds = grp[grp_list_index].commands;

        if (cmds[cmd_list_index].name) {
            while ((name = cmds[cmd_list_index].name)) {
                cmd_list_index++;

                if (STREQLEN(name, text, len))
                    return vshStrdup(NULL, name);
            }
        } else {
            cmd_list_index = 0;
            grp_list_index++;
        }
K
Karel Zak 已提交
20507 20508 20509 20510 20511 20512 20513
    }

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

static char *
20514 20515
vshReadlineOptionsGenerator(const char *text, int state)
{
K
Karel Zak 已提交
20516
    static int list_index, len;
20517
    static const vshCmdDef *cmd = NULL;
K
Karel Zak 已提交
20518
    const char *name;
K
Karel Zak 已提交
20519 20520 20521 20522 20523 20524 20525 20526 20527

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

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

20528
        cmdname = vshCalloc(NULL, (p - rl_line_buffer) + 1, 1);
20529
        memcpy(cmdname, rl_line_buffer, p - rl_line_buffer);
K
Karel Zak 已提交
20530 20531 20532

        cmd = vshCmddefSearch(cmdname);
        list_index = 0;
20533
        len = strlen(text);
20534
        VIR_FREE(cmdname);
K
Karel Zak 已提交
20535 20536 20537 20538
    }

    if (!cmd)
        return NULL;
20539

20540 20541 20542
    if (!cmd->opts)
        return NULL;

K
Karel Zak 已提交
20543
    while ((name = cmd->opts[list_index].name)) {
20544
        const vshCmdOptDef *opt = &cmd->opts[list_index];
K
Karel Zak 已提交
20545
        char *res;
20546

K
Karel Zak 已提交
20547
        list_index++;
20548

20549
        if (opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV)
K
Karel Zak 已提交
20550 20551
            /* ignore non --option */
            continue;
20552

K
Karel Zak 已提交
20553
        if (len > 2) {
20554
            if (STRNEQLEN(name, text + 2, len - 2))
K
Karel Zak 已提交
20555 20556
                continue;
        }
20557
        res = vshMalloc(NULL, strlen(name) + 3);
20558
        snprintf(res, strlen(name) + 3,  "--%s", name);
K
Karel Zak 已提交
20559 20560 20561 20562 20563 20564 20565 20566
        return res;
    }

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

static char **
20567 20568 20569
vshReadlineCompletion(const char *text, int start,
                      int end ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
20570 20571
    char **matches = (char **) NULL;

20572
    if (start == 0)
K
Karel Zak 已提交
20573
        /* command name generator */
20574
        matches = rl_completion_matches(text, vshReadlineCommandGenerator);
K
Karel Zak 已提交
20575 20576
    else
        /* commands options */
20577
        matches = rl_completion_matches(text, vshReadlineOptionsGenerator);
K
Karel Zak 已提交
20578 20579 20580 20581
    return matches;
}


20582 20583
static int
vshReadlineInit(vshControl *ctl)
20584
{
20585 20586
    char *userdir = NULL;

K
Karel Zak 已提交
20587 20588 20589 20590 20591
    /* 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;
20592 20593 20594

    /* Limit the total size of the history buffer */
    stifle_history(500);
20595

20596
    /* Prepare to read/write history from/to the $XDG_CACHE_HOME/virsh/history file */
20597
    userdir = virGetUserCacheDirectory();
20598

20599 20600
    if (userdir == NULL) {
        vshError(ctl, "%s", _("Could not determine home directory"));
20601
        return -1;
20602
    }
20603

20604
    if (virAsprintf(&ctl->historydir, "%s/virsh", userdir) < 0) {
20605
        vshError(ctl, "%s", _("Out of memory"));
20606
        VIR_FREE(userdir);
20607 20608 20609 20610 20611
        return -1;
    }

    if (virAsprintf(&ctl->historyfile, "%s/history", ctl->historydir) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
20612
        VIR_FREE(userdir);
20613 20614 20615
        return -1;
    }

20616
    VIR_FREE(userdir);
20617 20618 20619 20620 20621 20622 20623 20624 20625 20626 20627 20628 20629

    read_history(ctl->historyfile);

    return 0;
}

static void
vshReadlineDeinit (vshControl *ctl)
{
    if (ctl->historyfile != NULL) {
        if (mkdir(ctl->historydir, 0755) < 0 && errno != EEXIST) {
            char ebuf[1024];
            vshError(ctl, _("Failed to create '%s': %s"),
20630
                     ctl->historydir, virStrerror(errno, ebuf, sizeof(ebuf)));
E
Eric Blake 已提交
20631
        } else {
20632
            write_history(ctl->historyfile);
E
Eric Blake 已提交
20633
        }
20634 20635
    }

20636 20637
    VIR_FREE(ctl->historydir);
    VIR_FREE(ctl->historyfile);
K
Karel Zak 已提交
20638 20639
}

20640 20641 20642 20643 20644 20645
static char *
vshReadline (vshControl *ctl ATTRIBUTE_UNUSED, const char *prompt)
{
    return readline (prompt);
}

20646
#else /* !USE_READLINE */
20647

20648 20649 20650 20651 20652 20653 20654
static int
vshReadlineInit (vshControl *ctl ATTRIBUTE_UNUSED)
{
    /* empty */
    return 0;
}

20655
static void
20656
vshReadlineDeinit (vshControl *ctl ATTRIBUTE_UNUSED)
20657 20658 20659 20660 20661 20662 20663 20664 20665 20666 20667 20668
{
    /* empty */
}

static char *
vshReadline (vshControl *ctl, const char *prompt)
{
    char line[1024];
    char *r;
    int len;

    fputs (prompt, stdout);
20669
    r = fgets (line, sizeof(line), stdin);
20670 20671 20672 20673 20674 20675 20676 20677 20678 20679
    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);
}

20680
#endif /* !USE_READLINE */
20681

20682 20683 20684 20685 20686 20687
static void
vshDeinitTimer(int timer ATTRIBUTE_UNUSED, void *opaque ATTRIBUTE_UNUSED)
{
    /* nothing to be done here */
}

K
Karel Zak 已提交
20688
/*
J
Jim Meyering 已提交
20689
 * Deinitialize virsh
K
Karel Zak 已提交
20690
 */
E
Eric Blake 已提交
20691
static bool
20692
vshDeinit(vshControl *ctl)
20693
{
20694
    vshReadlineDeinit(ctl);
20695
    vshCloseLogFile(ctl);
20696
    VIR_FREE(ctl->name);
K
Karel Zak 已提交
20697
    if (ctl->conn) {
20698 20699 20700
        int ret;
        if ((ret = virConnectClose(ctl->conn)) != 0) {
            vshError(ctl, _("Failed to disconnect from the hypervisor, %d leaked reference(s)"), ret);
K
Karel Zak 已提交
20701 20702
        }
    }
D
Daniel P. Berrange 已提交
20703 20704
    virResetLastError();

J
Jiri Denemark 已提交
20705
    if (ctl->eventLoopStarted) {
20706 20707 20708 20709
        int timer;

        virMutexLock(&ctl->lock);
        ctl->quit = true;
J
Jiri Denemark 已提交
20710
        /* HACK: Add a dummy timeout to break event loop */
20711 20712 20713 20714 20715
        timer = virEventAddTimeout(0, vshDeinitTimer, NULL, NULL);
        virMutexUnlock(&ctl->lock);

        virThreadJoin(&ctl->eventLoop);

J
Jiri Denemark 已提交
20716 20717 20718 20719 20720 20721
        if (timer != -1)
            virEventRemoveTimeout(timer);

        ctl->eventLoopStarted = false;
    }

20722 20723
    virMutexDestroy(&ctl->lock);

E
Eric Blake 已提交
20724
    return true;
K
Karel Zak 已提交
20725
}
20726

K
Karel Zak 已提交
20727 20728 20729 20730
/*
 * Print usage
 */
static void
20731
vshUsage(void)
20732
{
20733
    const vshCmdGrp *grp;
20734
    const vshCmdDef *cmd;
20735

L
Lai Jiangshan 已提交
20736 20737
    fprintf(stdout, _("\n%s [options]... [<command_string>]"
                      "\n%s [options]... <command> [args...]\n\n"
20738
                      "  options:\n"
20739
                      "    -c | --connect=URI      hypervisor connection URI\n"
20740
                      "    -r | --readonly         connect readonly\n"
20741
                      "    -d | --debug=NUM        debug level [0-4]\n"
20742 20743 20744
                      "    -h | --help             this help\n"
                      "    -q | --quiet            quiet mode\n"
                      "    -t | --timing           print timing information\n"
20745 20746 20747 20748 20749
                      "    -l | --log=FILE         output logging to file\n"
                      "    -v                      short version\n"
                      "    -V                      long version\n"
                      "         --version[=TYPE]   version, TYPE is short or long (default short)\n"
                      "    -e | --escape <char>    set escape sequence for console\n\n"
20750
                      "  commands (non interactive mode):\n\n"), progname, progname);
20751

20752
    for (grp = cmdGroups; grp->name; grp++) {
E
Eric Blake 已提交
20753 20754 20755 20756 20757
        fprintf(stdout, _(" %s (help keyword '%s')\n"),
                grp->name, grp->keyword);
        for (cmd = grp->commands; cmd->name; cmd++) {
            if (cmd->flags & VSH_CMD_FLAG_ALIAS)
                continue;
20758
            fprintf(stdout,
E
Eric Blake 已提交
20759 20760 20761
                    "    %-30s %s\n", cmd->name,
                    _(vshCmddefGetInfo(cmd, "help")));
        }
20762 20763 20764 20765 20766
        fprintf(stdout, "\n");
    }

    fprintf(stdout, "%s",
            _("\n  (specify help <group> for details about the commands in the group)\n"));
20767 20768 20769
    fprintf(stdout, "%s",
            _("\n  (specify help <command> for details about the command)\n\n"));
    return;
K
Karel Zak 已提交
20770 20771
}

20772 20773 20774 20775 20776 20777 20778 20779 20780 20781
/*
 * Show version and options compiled in
 */
static void
vshShowVersion(vshControl *ctl ATTRIBUTE_UNUSED)
{
    /* FIXME - list a copyright blurb, as in GNU programs?  */
    vshPrint(ctl, _("Virsh command line tool of libvirt %s\n"), VERSION);
    vshPrint(ctl, _("See web site at %s\n\n"), "http://libvirt.org/");

L
Laine Stump 已提交
20782 20783
    vshPrint(ctl, "%s", _("Compiled with support for:\n"));
    vshPrint(ctl, "%s", _(" Hypervisors:"));
20784 20785 20786
#ifdef WITH_QEMU
    vshPrint(ctl, " QEmu/KVM");
#endif
D
Doug Goldstein 已提交
20787 20788 20789
#ifdef WITH_LXC
    vshPrint(ctl, " LXC");
#endif
20790 20791 20792
#ifdef WITH_UML
    vshPrint(ctl, " UML");
#endif
D
Doug Goldstein 已提交
20793 20794 20795 20796 20797 20798
#ifdef WITH_XEN
    vshPrint(ctl, " Xen");
#endif
#ifdef WITH_LIBXL
    vshPrint(ctl, " LibXL");
#endif
20799 20800 20801
#ifdef WITH_OPENVZ
    vshPrint(ctl, " OpenVZ");
#endif
D
Doug Goldstein 已提交
20802 20803
#ifdef WITH_VMWARE
    vshPrint(ctl, " VMWare");
20804
#endif
D
Doug Goldstein 已提交
20805 20806
#ifdef WITH_PHYP
    vshPrint(ctl, " PHYP");
20807
#endif
D
Doug Goldstein 已提交
20808 20809
#ifdef WITH_VBOX
    vshPrint(ctl, " VirtualBox");
20810 20811 20812 20813
#endif
#ifdef WITH_ESX
    vshPrint(ctl, " ESX");
#endif
D
Doug Goldstein 已提交
20814 20815
#ifdef WITH_HYPERV
    vshPrint(ctl, " Hyper-V");
20816
#endif
D
Doug Goldstein 已提交
20817 20818
#ifdef WITH_XENAPI
    vshPrint(ctl, " XenAPI");
20819 20820 20821 20822 20823 20824
#endif
#ifdef WITH_TEST
    vshPrint(ctl, " Test");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
20825
    vshPrint(ctl, "%s", _(" Networking:"));
20826 20827 20828 20829 20830 20831 20832 20833 20834 20835 20836 20837 20838
#ifdef WITH_REMOTE
    vshPrint(ctl, " Remote");
#endif
#ifdef WITH_LIBVIRTD
    vshPrint(ctl, " Daemon");
#endif
#ifdef WITH_NETWORK
    vshPrint(ctl, " Network");
#endif
#ifdef WITH_BRIDGE
    vshPrint(ctl, " Bridging");
#endif
#ifdef WITH_NETCF
D
Doug Goldstein 已提交
20839
    vshPrint(ctl, " Interface");
20840 20841 20842 20843 20844 20845 20846 20847 20848
#endif
#ifdef WITH_NWFILTER
    vshPrint(ctl, " Nwfilter");
#endif
#ifdef WITH_VIRTUALPORT
    vshPrint(ctl, " VirtualPort");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
20849
    vshPrint(ctl, "%s", _(" Storage:"));
20850 20851 20852 20853 20854 20855 20856 20857 20858 20859 20860 20861 20862 20863 20864 20865 20866 20867 20868 20869
#ifdef WITH_STORAGE_DIR
    vshPrint(ctl, " Dir");
#endif
#ifdef WITH_STORAGE_DISK
    vshPrint(ctl, " Disk");
#endif
#ifdef WITH_STORAGE_FS
    vshPrint(ctl, " Filesystem");
#endif
#ifdef WITH_STORAGE_SCSI
    vshPrint(ctl, " SCSI");
#endif
#ifdef WITH_STORAGE_MPATH
    vshPrint(ctl, " Multipath");
#endif
#ifdef WITH_STORAGE_ISCSI
    vshPrint(ctl, " iSCSI");
#endif
#ifdef WITH_STORAGE_LVM
    vshPrint(ctl, " LVM");
20870 20871 20872
#endif
#ifdef WITH_STORAGE_RBD
    vshPrint(ctl, " RBD");
20873 20874 20875
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
20876
    vshPrint(ctl, "%s", _(" Miscellaneous:"));
D
Doug Goldstein 已提交
20877 20878 20879
#ifdef WITH_NODE_DEVICES
    vshPrint(ctl, " Nodedev");
#endif
20880
#ifdef WITH_SECDRIVER_APPARMOR
20881 20882 20883 20884 20885 20886 20887 20888 20889 20890 20891
    vshPrint(ctl, " AppArmor");
#endif
#ifdef WITH_SECDRIVER_SELINUX
    vshPrint(ctl, " SELinux");
#endif
#ifdef WITH_SECRETS
    vshPrint(ctl, " Secrets");
#endif
#ifdef ENABLE_DEBUG
    vshPrint(ctl, " Debug");
#endif
D
Doug Goldstein 已提交
20892
#ifdef WITH_DTRACE_PROBES
20893 20894 20895 20896 20897 20898 20899 20900 20901 20902 20903
    vshPrint(ctl, " DTrace");
#endif
#ifdef USE_READLINE
    vshPrint(ctl, " Readline");
#endif
#ifdef WITH_DRIVER_MODULES
    vshPrint(ctl, " Modular");
#endif
    vshPrint(ctl, "\n");
}

20904 20905 20906 20907 20908 20909 20910 20911 20912 20913
static bool
vshAllowedEscapeChar(char c)
{
    /* Allowed escape characters:
     * a-z A-Z @ [ \ ] ^ _
     */
    return ('a' <= c && c <= 'z') ||
        ('@' <= c && c <= '_');
}

K
Karel Zak 已提交
20914 20915 20916 20917
/*
 * argv[]:  virsh [options] [command]
 *
 */
E
Eric Blake 已提交
20918
static bool
20919
vshParseArgv(vshControl *ctl, int argc, char **argv)
20920
{
20921
    int arg, len;
K
Karel Zak 已提交
20922
    struct option opt[] = {
E
Eric Blake 已提交
20923 20924 20925 20926 20927 20928 20929 20930
        {"debug", required_argument, NULL, 'd'},
        {"help", no_argument, NULL, 'h'},
        {"quiet", no_argument, NULL, 'q'},
        {"timing", no_argument, NULL, 't'},
        {"version", optional_argument, NULL, 'v'},
        {"connect", required_argument, NULL, 'c'},
        {"readonly", no_argument, NULL, 'r'},
        {"log", required_argument, NULL, 'l'},
20931
        {"escape", required_argument, NULL, 'e'},
E
Eric Blake 已提交
20932
        {NULL, 0, NULL, 0}
20933 20934
    };

20935 20936 20937
    /* Standard (non-command) options. The leading + ensures that no
     * argument reordering takes place, so that command options are
     * not confused with top-level virsh options. */
20938
    while ((arg = getopt_long(argc, argv, "+d:hqtc:vVrl:e:", opt, NULL)) != -1) {
20939
        switch (arg) {
20940
        case 'd':
D
Daniel Veillard 已提交
20941
            if (virStrToLong_i(optarg, NULL, 10, &ctl->debug) < 0) {
L
Laine Stump 已提交
20942
                vshError(ctl, "%s", _("option -d takes a numeric argument"));
D
Daniel Veillard 已提交
20943 20944
                exit(EXIT_FAILURE);
            }
20945 20946
            break;
        case 'h':
E
Eric Blake 已提交
20947 20948
            vshUsage();
            exit(EXIT_SUCCESS);
20949 20950
            break;
        case 'q':
E
Eric Blake 已提交
20951
            ctl->quiet = true;
20952 20953
            break;
        case 't':
E
Eric Blake 已提交
20954
            ctl->timing = true;
20955 20956 20957 20958
            break;
        case 'c':
            ctl->name = vshStrdup(ctl, optarg);
            break;
E
Eric Blake 已提交
20959 20960 20961 20962 20963 20964
        case 'v':
            if (STRNEQ_NULLABLE(optarg, "long")) {
                puts(VERSION);
                exit(EXIT_SUCCESS);
            }
            /* fall through */
20965 20966 20967
        case 'V':
            vshShowVersion(ctl);
            exit(EXIT_SUCCESS);
20968
        case 'r':
E
Eric Blake 已提交
20969
            ctl->readonly = true;
20970
            break;
20971 20972 20973
        case 'l':
            ctl->logfile = vshStrdup(ctl, optarg);
            break;
20974 20975 20976
        case 'e':
            len = strlen(optarg);

20977 20978
            if ((len == 2 && *optarg == '^' &&
                 vshAllowedEscapeChar(optarg[1])) ||
20979 20980 20981 20982 20983 20984 20985 20986
                (len == 1 && *optarg != '^')) {
                ctl->escapeChar = optarg;
            } else {
                vshError(ctl, _("Invalid string '%s' for escape sequence"),
                         optarg);
                exit(EXIT_FAILURE);
            }
            break;
20987
        default:
20988 20989
            vshError(ctl, _("unsupported option '-%c'. See --help."), arg);
            exit(EXIT_FAILURE);
K
Karel Zak 已提交
20990 20991 20992
        }
    }

20993
    if (argc > optind) {
K
Karel Zak 已提交
20994
        /* parse command */
E
Eric Blake 已提交
20995
        ctl->imode = false;
20996
        if (argc - optind == 1) {
20997
            vshDebug(ctl, VSH_ERR_INFO, "commands: \"%s\"\n", argv[optind]);
20998
            return vshCommandStringParse(ctl, argv[optind]);
L
Lai Jiangshan 已提交
20999
        } else {
21000
            return vshCommandArgvParse(ctl, argc - optind, argv + optind);
K
Karel Zak 已提交
21001 21002
        }
    }
E
Eric Blake 已提交
21003
    return true;
K
Karel Zak 已提交
21004 21005
}

21006 21007 21008 21009
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
21010
    char *defaultConn;
E
Eric Blake 已提交
21011
    bool ret = true;
K
Karel Zak 已提交
21012

21013 21014 21015
    memset(ctl, 0, sizeof(vshControl));
    ctl->imode = true;          /* default is interactive mode */
    ctl->log_fd = -1;           /* Initialize log file descriptor */
J
Jiri Denemark 已提交
21016
    ctl->debug = VSH_DEBUG_DEFAULT;
21017 21018
    ctl->escapeChar = CTRL_CLOSE_BRACKET;

21019

21020 21021
    if (!setlocale(LC_ALL, "")) {
        perror("setlocale");
21022
        /* failure to setup locale is not fatal */
21023
    }
21024
    if (!bindtextdomain(PACKAGE, LOCALEDIR)) {
21025
        perror("bindtextdomain");
E
Eric Blake 已提交
21026
        return EXIT_FAILURE;
21027
    }
21028
    if (!textdomain(PACKAGE)) {
21029
        perror("textdomain");
E
Eric Blake 已提交
21030
        return EXIT_FAILURE;
21031 21032
    }

21033 21034 21035 21036 21037
    if (virMutexInit(&ctl->lock) < 0) {
        vshError(ctl, "%s", _("Failed to initialize mutex"));
        return EXIT_FAILURE;
    }

21038 21039 21040 21041 21042
    if (virInitialize() < 0) {
        vshError(ctl, "%s", _("Failed to initialize libvirt"));
        return EXIT_FAILURE;
    }

21043
    if (!(progname = strrchr(argv[0], '/')))
K
Karel Zak 已提交
21044 21045 21046
        progname = argv[0];
    else
        progname++;
21047

21048
    if ((defaultConn = getenv("VIRSH_DEFAULT_CONNECT_URI"))) {
E
Eric Blake 已提交
21049
        ctl->name = vshStrdup(ctl, defaultConn);
21050 21051
    }

D
Daniel P. Berrange 已提交
21052 21053
    if (!vshParseArgv(ctl, argc, argv)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
21054
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
21055
    }
21056

D
Daniel P. Berrange 已提交
21057 21058
    if (!vshInit(ctl)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
21059
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
21060
    }
21061

K
Karel Zak 已提交
21062
    if (!ctl->imode) {
21063
        ret = vshCommandRun(ctl, ctl->cmd);
21064
    } else {
K
Karel Zak 已提交
21065 21066
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
21067
            vshPrint(ctl,
21068
                     _("Welcome to %s, the virtualization interactive terminal.\n\n"),
21069
                     progname);
J
Jim Meyering 已提交
21070
            vshPrint(ctl, "%s",
21071
                     _("Type:  'help' for help with commands\n"
21072
                       "       'quit' to quit\n\n"));
K
Karel Zak 已提交
21073
        }
21074 21075 21076 21077 21078 21079

        if (vshReadlineInit(ctl) < 0) {
            vshDeinit(ctl);
            exit(EXIT_FAILURE);
        }

K
Karel Zak 已提交
21080
        do {
21081
            const char *prompt = ctl->readonly ? VSH_PROMPT_RO : VSH_PROMPT_RW;
21082
            ctl->cmdstr =
21083
                vshReadline(ctl, prompt);
21084 21085
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
21086
            if (*ctl->cmdstr) {
21087
#if USE_READLINE
K
Karel Zak 已提交
21088
                add_history(ctl->cmdstr);
21089
#endif
21090
                if (vshCommandStringParse(ctl, ctl->cmdstr))
K
Karel Zak 已提交
21091 21092
                    vshCommandRun(ctl, ctl->cmd);
            }
21093
            VIR_FREE(ctl->cmdstr);
21094
        } while (ctl->imode);
K
Karel Zak 已提交
21095

21096 21097
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
21098
    }
21099

K
Karel Zak 已提交
21100 21101
    vshDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
21102
}