virsh.c 200.9 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
#include "conf/virdomainlist.h"
K
Karel Zak 已提交
68 69 70

static char *progname;

71 72
#define VIRSH_MAX_XML_FILE 10*1024*1024

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

76 77
#define VIR_FROM_THIS VIR_FROM_NONE

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

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

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

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

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

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

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
/*
 * 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 已提交
163 164 165
/*
 * Command Option Flags
 */
E
Eric Blake 已提交
166 167 168 169
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 已提交
170
    VSH_OFLAG_REQ_OPT  = (1 << 2), /* --optionname required */
E
Eric Blake 已提交
171
};
K
Karel Zak 已提交
172 173 174 175 176 177

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

/*
E
Eric Blake 已提交
178 179 180 181 182
 * 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 已提交
183
 */
184
typedef struct {
E
Eric Blake 已提交
185 186
    const char *name;           /* name of information, or NULL for list end */
    const char *data;           /* non-NULL information */
K
Karel Zak 已提交
187 188 189 190 191
} vshCmdInfo;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

341
static virNWFilterPtr vshCommandOptNWFilterBy(vshControl *ctl, const vshCmd *cmd,
342
                                                  const char **name, int flag);
343 344 345 346 347 348

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

349
static virSecretPtr vshCommandOptSecret(vshControl *ctl, const vshCmd *cmd,
350
                                        const char **name);
351

352
static void vshPrintExtra(vshControl *ctl, const char *format, ...)
353
    ATTRIBUTE_FMT_PRINTF(2, 3);
354
static void vshDebug(vshControl *ctl, int level, const char *format, ...)
355
    ATTRIBUTE_FMT_PRINTF(3, 4);
K
Karel Zak 已提交
356 357

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

360
static int vshDomainState(vshControl *ctl, virDomainPtr dom, int *reason);
K
Karel Zak 已提交
361
static const char *vshDomainStateToString(int state);
362
static const char *vshDomainStateReasonToString(int state, int reason);
363
static const char *vshDomainControlStateToString(int state);
364
static const char *vshDomainVcpuStateToString(int state);
E
Eric Blake 已提交
365
static bool vshConnectionUsability(vshControl *ctl, virConnectPtr conn);
366 367 368
static virTypedParameterPtr vshFindTypedParamByName(const char *name,
                                                    virTypedParameterPtr list,
                                                    int count);
369 370
static char *vshGetTypedParamValue(vshControl *ctl, virTypedParameterPtr item)
    ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2);
K
Karel Zak 已提交
371

E
Eric Blake 已提交
372 373 374
static char *editWriteToTempFile(vshControl *ctl, const char *doc);
static int   editFile(vshControl *ctl, const char *filename);
static char *editReadBackFile(vshControl *ctl, const char *filename);
375

376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
/* 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);

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

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

405
static char *_vshStrdup(vshControl *ctl, const char *s, const char *filename, int line);
406 407
#define vshStrdup(_ctl, _s)    _vshStrdup(_ctl, _s, __FILE__, __LINE__)

408 409
static int parseRateStr(const char *rateStr, virNetDevBandwidthRatePtr rate);

E
Eric Blake 已提交
410 411 412
static void *
_vshMalloc(vshControl *ctl, size_t size, const char *filename, int line)
{
E
Eric Blake 已提交
413
    char *x;
E
Eric Blake 已提交
414

E
Eric Blake 已提交
415
    if (VIR_ALLOC_N(x, size) == 0)
E
Eric Blake 已提交
416 417 418 419 420 421 422 423 424
        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 已提交
425
    char *x;
E
Eric Blake 已提交
426

E
Eric Blake 已提交
427 428
    if (!xalloc_oversized(nmemb, size) &&
        VIR_ALLOC_N(x, nmemb * size) == 0)
E
Eric Blake 已提交
429 430 431 432 433 434 435 436 437 438 439 440
        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)
441
        return NULL;
E
Eric Blake 已提交
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
    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
458

459 460 461 462 463
static int
vshNameSorter(const void *a, const void *b)
{
    const char **sa = (const char**)a;
    const char **sb = (const char**)b;
464

465 466
    /* User visible sort, so we want locale-specific case comparison. */
    return strcasecmp(*sa, *sb);
467 468
}

469 470 471 472 473 474 475
static double
prettyCapacity(unsigned long long val,
               const char **unit) {
    if (val < 1024) {
        *unit = "";
        return (double)val;
    } else if (val < (1024.0l * 1024.0l)) {
476
        *unit = "KiB";
477 478
        return (((double)val / 1024.0l));
    } else if (val < (1024.0l * 1024.0l * 1024.0l)) {
479
        *unit = "MiB";
480
        return (double)val / (1024.0l * 1024.0l);
481
    } else if (val < (1024.0l * 1024.0l * 1024.0l * 1024.0l)) {
482
        *unit = "GiB";
483
        return (double)val / (1024.0l * 1024.0l * 1024.0l);
484
    } else {
485
        *unit = "TiB";
486
        return (double)val / (1024.0l * 1024.0l * 1024.0l * 1024.0l);
487 488 489 490
    }
}


J
John Levon 已提交
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
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)
{
516 517 518 519 520 521 522 523
    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)
524
            goto out;
525
    }
J
John Levon 已提交
526 527

    if (last_error->code == VIR_ERR_OK) {
528
        vshError(ctl, "%s", _("unknown error"));
J
John Levon 已提交
529 530 531
        goto out;
    }

532
    vshError(ctl, "%s", last_error->message);
J
John Levon 已提交
533 534 535 536 537 538

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

539 540 541 542 543 544 545 546 547
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;
}

548 549 550 551 552
/*
 * Detection of disconnections and automatic reconnection support
 */
static int disconnected = 0; /* we may have been disconnected */

553 554 555 556 557
/* Gnulib doesn't guarantee SA_SIGINFO support.  */
#ifndef SA_SIGINFO
# define SA_SIGINFO 0
#endif

558 559 560 561 562 563
/*
 * 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
 */
564 565
static void vshCatchDisconnect(int sig, siginfo_t *siginfo,
                               void *context ATTRIBUTE_UNUSED) {
E
Eric Blake 已提交
566
    if (sig == SIGPIPE ||
567
        (SA_SIGINFO && siginfo->si_signo == SIGPIPE))
568 569 570 571 572 573 574 575 576
        disconnected++;
}

/*
 * vshSetupSignals:
 *
 * Catch SIGPIPE signals which may arise when disconnection
 * from libvirtd occurs
 */
L
Laine Stump 已提交
577
static void
578 579 580 581 582 583 584 585 586 587 588 589 590
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 已提交
591
 * Reconnect after a disconnect from libvirtd
592 593
 *
 */
L
Laine Stump 已提交
594
static void
595 596 597 598 599 600
vshReconnect(vshControl *ctl)
{
    bool connected = false;

    if (ctl->conn != NULL) {
        connected = true;
601
        virConnectClose(ctl->conn);
602
    }
603 604 605 606 607 608

    ctl->conn = virConnectOpenAuth(ctl->name,
                                   virConnectAuthPtrDefault,
                                   ctl->readonly ? VIR_CONNECT_RO : 0);
    if (!ctl->conn)
        vshError(ctl, "%s", _("Failed to reconnect to the hypervisor"));
609
    else if (connected)
610 611
        vshError(ctl, "%s", _("Reconnected to the hypervisor"));
    disconnected = 0;
612
    ctl->useGetInfo = false;
613
    ctl->useSnapshotOld = false;
614
}
615

616
#ifndef WIN32
617 618 619 620 621 622 623 624 625 626 627 628 629
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);
}

630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
/**
 * 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 == '?') {
664 665 666 667 668 669 670
            vshPrintRaw(ctl,
                        "",
                        _("y - yes, start editor again"),
                        _("n - no, throw away my changes"),
                        _("f - force, try to redefine again"),
                        _("? - print this help"),
                        NULL);
671 672 673 674 675 676 677 678 679 680
            continue;
        } else if (c == 'y' || c == 'n' || c == 'f') {
            break;
        }
    }

    tcsetattr(STDIN_FILENO, TCSAFLUSH, &ttyattr);

    vshPrint(ctl, "\r\n");
    return c;
681 682 683 684 685
}
#else /* WIN32 */
static int
vshAskReedit(vshControl *ctl, const char *msg ATTRIBUTE_UNUSED)
{
686 687 688 689
    vshDebug(ctl, VSH_ERR_WARNING, "%s", _("This function is not "
                                           "supported on WIN32 platform"));
    return 0;
}
690
#endif /* WIN32 */
691

692 693 694 695 696 697 698 699
static int vshStreamSink(virStreamPtr st ATTRIBUTE_UNUSED,
                         const char *bytes, size_t nbytes, void *opaque)
{
    int *fd = opaque;

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

K
Karel Zak 已提交
700 701 702 703 704 705
/* ---------------
 * Commands
 * ---------------
 */

/*
706
 * "help" command
K
Karel Zak 已提交
707
 */
708
static const vshCmdInfo info_help[] = {
709
    {"help", N_("print help")},
710 711
    {"desc", N_("Prints global help, command specific help, or help for a\n"
                "    group of related commands")},
712

713
    {NULL, NULL}
K
Karel Zak 已提交
714 715
};

716
static const vshCmdOptDef opts_help[] = {
717
    {"command", VSH_OT_DATA, 0, N_("Prints global help, command specific help, or help for a group of related commands")},
718
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
719 720
};

E
Eric Blake 已提交
721
static bool
722
cmdHelp(vshControl *ctl, const vshCmd *cmd)
723
 {
724
    const char *name = NULL;
725

726
    if (vshCommandOptString(cmd, "command", &name) <= 0) {
727
        const vshCmdGrp *grp;
728
        const vshCmdDef *def;
729

730 731 732 733 734 735
        vshPrint(ctl, "%s", _("Grouped commands:\n\n"));

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

736 737 738
            for (def = grp->commands; def->name; def++) {
                if (def->flags & VSH_CMD_FLAG_ALIAS)
                    continue;
739 740
                vshPrint(ctl, "    %-30s %s\n", def->name,
                         _(vshCmddefGetInfo(def, "help")));
741
            }
742 743 744 745

            vshPrint(ctl, "\n");
        }

E
Eric Blake 已提交
746
        return true;
747
    }
748

E
Eric Blake 已提交
749
    if (vshCmddefSearch(name)) {
750
        return vshCmddefHelp(ctl, name);
E
Eric Blake 已提交
751
    } else if (vshCmdGrpSearch(name)) {
752 753 754
        return vshCmdGrpHelp(ctl, name);
    } else {
        vshError(ctl, _("command or command group '%s' doesn't exist"), name);
E
Eric Blake 已提交
755
        return false;
K
Karel Zak 已提交
756 757 758 759
    }
}

/*
760
 * "connect" command
K
Karel Zak 已提交
761
 */
762
static const vshCmdInfo info_connect[] = {
763
    {"help", N_("(re)connect to hypervisor")},
764
    {"desc",
765
     N_("Connect to local hypervisor. This is built-in command after shell start up.")},
766
    {NULL, NULL}
K
Karel Zak 已提交
767 768
};

769
static const vshCmdOptDef opts_connect[] = {
E
Eric Blake 已提交
770 771
    {"name",     VSH_OT_DATA, VSH_OFLAG_EMPTY_OK,
     N_("hypervisor connection URI")},
772
    {"readonly", VSH_OT_BOOL, 0, N_("read-only connection")},
773
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
774 775
};

E
Eric Blake 已提交
776
static bool
777
cmdConnect(vshControl *ctl, const vshCmd *cmd)
778
{
E
Eric Blake 已提交
779
    bool ro = vshCommandOptBool(cmd, "readonly");
780
    const char *name = NULL;
781

K
Karel Zak 已提交
782
    if (ctl->conn) {
783 784 785
        int ret;
        if ((ret = virConnectClose(ctl->conn)) != 0) {
            vshError(ctl, _("Failed to disconnect from the hypervisor, %d leaked reference(s)"), ret);
E
Eric Blake 已提交
786
            return false;
K
Karel Zak 已提交
787 788 789
        }
        ctl->conn = NULL;
    }
790

791
    VIR_FREE(ctl->name);
792 793
    if (vshCommandOptString(cmd, "name", &name) < 0) {
        vshError(ctl, "%s", _("Please specify valid connection URI"));
E
Eric Blake 已提交
794
        return false;
795
    }
796
    ctl->name = vshStrdup(ctl, name);
K
Karel Zak 已提交
797

798
    ctl->useGetInfo = false;
799
    ctl->useSnapshotOld = false;
E
Eric Blake 已提交
800
    ctl->readonly = ro;
K
Karel Zak 已提交
801

802 803 804
    ctl->conn = virConnectOpenAuth(ctl->name, virConnectAuthPtrDefault,
                                   ctl->readonly ? VIR_CONNECT_RO : 0);

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

E
Eric Blake 已提交
808
    return !!ctl->conn;
K
Karel Zak 已提交
809 810
}

811
/*
812
 * "freecell" command
813
 */
814 815 816
static const vshCmdInfo info_freecell[] = {
    {"help", N_("NUMA free memory")},
    {"desc", N_("display available free memory for the NUMA cell.")},
817 818 819
    {NULL, NULL}
};

820 821 822
static const vshCmdOptDef opts_freecell[] = {
    {"cellno", VSH_OT_INT, 0, N_("NUMA cell number")},
    {"all", VSH_OT_BOOL, 0, N_("show free memory for all NUMA cells")},
823 824 825
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
826
static bool
827
cmdFreecell(vshControl *ctl, const vshCmd *cmd)
828
{
829 830 831 832 833 834 835 836 837 838 839 840 841
    bool func_ret = false;
    int ret;
    int cell = -1, cell_given;
    unsigned long long memory;
    xmlNodePtr *nodes = NULL;
    unsigned long nodes_cnt;
    unsigned long *nodes_id = NULL;
    unsigned long long *nodes_free = NULL;
    int all_given;
    int i;
    char *cap_xml = NULL;
    xmlDocPtr xml = NULL;
    xmlXPathContextPtr ctxt = NULL;
842

843

844 845 846 847 848
    if (!vshConnectionUsability(ctl, ctl->conn))
        return false;

    if ( (cell_given = vshCommandOptInt(cmd, "cellno", &cell)) < 0) {
        vshError(ctl, "%s", _("cell number has to be a number"));
849 850
        goto cleanup;
    }
851
    all_given = vshCommandOptBool(cmd, "all");
852

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

859 860 861 862 863 864
    if (all_given) {
        cap_xml = virConnectGetCapabilities(ctl->conn);
        if (!cap_xml) {
            vshError(ctl, "%s", _("unable to get node capabilities"));
            goto cleanup;
        }
865

866 867 868 869 870 871 872
        xml = virXMLParseStringCtxt(cap_xml, _("(capabilities)"), &ctxt);
        if (!xml) {
            vshError(ctl, "%s", _("unable to get node capabilities"));
            goto cleanup;
        }
        nodes_cnt = virXPathNodeSet("/capabilities/host/topology/cells/cell",
                                    ctxt, &nodes);
873

874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
        if (nodes_cnt == -1) {
            vshError(ctl, "%s", _("could not get information about "
                                  "NUMA topology"));
            goto cleanup;
        }

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

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

        vshPrintExtra(ctl, "--------------------\n");
        vshPrintExtra(ctl, "%5s: %10llu KiB\n", _("Total"), memory/1024);
    } else {
        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)
            vshPrint(ctl, "%s: %llu KiB\n", _("Total"), (memory/1024));
        else
            vshPrint(ctl, "%d: %llu KiB\n", cell, (memory/1024));
    }

    func_ret = true;

cleanup:
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml);
    VIR_FREE(nodes);
    VIR_FREE(nodes_free);
    VIR_FREE(nodes_id);
    VIR_FREE(cap_xml);
    return func_ret;
937 938
}

939 940 941 942 943 944 945 946 947
/*
 * "nodeinfo" command
 */
static const vshCmdInfo info_nodeinfo[] = {
    {"help", N_("node information")},
    {"desc", N_("Returns basic information about the node.")},
    {NULL, NULL}
};

E
Eric Blake 已提交
948
static bool
949
cmdNodeinfo(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
950
{
951
    virNodeInfo info;
952

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

956 957
    if (virNodeGetInfo(ctl->conn, &info) < 0) {
        vshError(ctl, "%s", _("failed to get node information"));
E
Eric Blake 已提交
958
        return false;
959
    }
960 961 962 963 964 965 966 967
    vshPrint(ctl, "%-20s %s\n", _("CPU model:"), info.model);
    vshPrint(ctl, "%-20s %d\n", _("CPU(s):"), info.cpus);
    vshPrint(ctl, "%-20s %d MHz\n", _("CPU frequency:"), info.mhz);
    vshPrint(ctl, "%-20s %d\n", _("CPU socket(s):"), info.sockets);
    vshPrint(ctl, "%-20s %d\n", _("Core(s) per socket:"), info.cores);
    vshPrint(ctl, "%-20s %d\n", _("Thread(s) per core:"), info.threads);
    vshPrint(ctl, "%-20s %d\n", _("NUMA cell(s):"), info.nodes);
    vshPrint(ctl, "%-20s %lu KiB\n", _("Memory size:"), info.memory);
968

969
    return true;
970 971
}

972
/*
973
 * "nodecpustats" command
974
 */
975 976 977
static const vshCmdInfo info_nodecpustats[] = {
    {"help", N_("Prints cpu stats of the node.")},
    {"desc", N_("Returns cpu stats of the node, in nanoseconds.")},
978 979 980
    {NULL, NULL}
};

981 982 983
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.")},
984 985 986 987
    {NULL, 0, 0, NULL}
};

static bool
988
cmdNodeCpuStats(vshControl *ctl, const vshCmd *cmd)
989
{
990 991 992 993 994 995
    int i, j;
    bool flag_utilization = false;
    bool flag_percent = vshCommandOptBool(cmd, "percent");
    int cpuNum = VIR_NODE_CPU_STATS_ALL_CPUS;
    virNodeCPUStatsPtr params;
    int nparams = 0;
996
    bool ret = false;
997 998 999 1000 1001 1002 1003 1004 1005
    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;
1006

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

1010 1011
    if (vshCommandOptInt(cmd, "cpu", &cpuNum) < 0) {
        vshError(ctl, "%s", _("Invalid value of cpuNum"));
1012
        return false;
1013
    }
1014

1015 1016 1017 1018
    if (virNodeGetCPUStats(ctl->conn, cpuNum, NULL, &nparams, 0) != 0) {
        vshError(ctl, "%s",
                 _("Unable to get number of cpu stats"));
        return false;
1019
    }
1020 1021 1022
    if (nparams == 0) {
        /* nothing to output */
        return true;
1023
    }
1024

1025 1026
    memset(cpu_stats, 0, sizeof(cpu_stats));
    params = vshCalloc(ctl, nparams, sizeof(*params));
1027

1028 1029 1030
    for (i = 0; i < 2; i++) {
        if (i > 0)
            sleep(1);
1031

1032 1033 1034
        if (virNodeGetCPUStats(ctl->conn, cpuNum, params, &nparams, 0) != 0) {
            vshError(ctl, "%s", _("Unable to get node cpu stats"));
            goto cleanup;
1035 1036
        }

1037 1038
        for (j = 0; j < nparams; j++) {
            unsigned long long value = params[j].value;
1039

1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
            if (STREQ(params[j].field, VIR_NODE_CPU_STATS_KERNEL)) {
                cpu_stats[i].sys = value;
            } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_USER)) {
                cpu_stats[i].user = value;
            } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_IDLE)) {
                cpu_stats[i].idle = value;
            } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_IOWAIT)) {
                cpu_stats[i].iowait = value;
            } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_UTILIZATION)) {
                cpu_stats[i].util = value;
                flag_utilization = true;
            }
        }

        if (flag_utilization || !flag_percent)
            break;
1056
    }
1057

1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
    if (!flag_percent) {
        if (!flag_utilization) {
            vshPrint(ctl, "%-15s %20llu\n", _("user:"), cpu_stats[0].user);
            vshPrint(ctl, "%-15s %20llu\n", _("system:"), cpu_stats[0].sys);
            vshPrint(ctl, "%-15s %20llu\n", _("idle:"), cpu_stats[0].idle);
            vshPrint(ctl, "%-15s %20llu\n", _("iowait:"), cpu_stats[0].iowait);
        }
    } else {
        if (flag_utilization) {
            usage = cpu_stats[0].util;
1068

1069 1070 1071 1072 1073 1074 1075 1076
            vshPrint(ctl, "%-15s %5.1lf%%\n", _("usage:"), usage);
            vshPrint(ctl, "%-15s %5.1lf%%\n", _("idle:"), 100 - usage);
        } 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;
1077

1078
            usage = (user_time + sys_time) / total_time * 100;
1079

1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
            vshPrint(ctl, "%-15s %5.1lf%%\n",
                     _("usage:"), usage);
            vshPrint(ctl, "%-15s %5.1lf%%\n",
                     _("user:"), user_time / total_time * 100);
            vshPrint(ctl, "%-15s %5.1lf%%\n",
                     _("system:"), sys_time  / total_time * 100);
            vshPrint(ctl, "%-15s %5.1lf%%\n",
                     _("idle:"), idle_time     / total_time * 100);
            vshPrint(ctl, "%-15s %5.1lf%%\n",
                     _("iowait:"), iowait_time   / total_time * 100);
1090 1091
        }
    }
1092

1093
    ret = true;
1094 1095 1096

  cleanup:
    VIR_FREE(params);
1097 1098 1099
    return ret;
}

1100
/*
1101
 * "nodememstats" command
1102
 */
1103 1104 1105
static const vshCmdInfo info_nodememstats[] = {
    {"help", N_("Prints memory stats of the node.")},
    {"desc", N_("Returns memory stats of the node, in kilobytes.")},
1106 1107 1108
    {NULL, NULL}
};

1109 1110
static const vshCmdOptDef opts_node_memstats[] = {
    {"cell", VSH_OT_INT, 0, N_("prints specified cell statistics only.")},
1111 1112 1113
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
1114
static bool
1115
cmdNodeMemStats(vshControl *ctl, const vshCmd *cmd)
1116
{
1117 1118 1119 1120
    int nparams = 0;
    unsigned int i = 0;
    int cellNum = VIR_NODE_MEMORY_STATS_ALL_CELLS;
    virNodeMemoryStatsPtr params = NULL;
1121
    bool ret = false;
1122

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

1126 1127 1128
    if (vshCommandOptInt(cmd, "cell", &cellNum) < 0) {
        vshError(ctl, "%s", _("Invalid value of cellNum"));
        return false;
1129
    }
1130

1131 1132 1133 1134
    /* 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"));
1135 1136 1137
        goto cleanup;
    }

1138 1139 1140
    if (nparams == 0) {
        /* nothing to output */
        ret = true;
1141 1142
        goto cleanup;
    }
1143

1144 1145 1146 1147
    /* 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"));
1148 1149
        goto cleanup;
    }
1150

1151 1152
    for (i = 0; i < nparams; i++)
        vshPrint(ctl, "%-7s: %20llu KiB\n", params[i].field, params[i].value);
1153

1154
    ret = true;
1155

1156 1157 1158 1159
  cleanup:
    VIR_FREE(params);
    return ret;
}
1160

1161 1162 1163 1164 1165 1166 1167 1168 1169
/*
 * "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}
};
1170

1171 1172 1173 1174 1175 1176 1177
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}
};
1178

1179 1180 1181 1182 1183 1184 1185
static bool
cmdNodeSuspend(vshControl *ctl, const vshCmd *cmd)
{
    const char *target = NULL;
    unsigned int suspendTarget;
    long long duration;
    unsigned int flags = 0;
1186

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

1190 1191 1192
    if (vshCommandOptString(cmd, "target", &target) < 0) {
        vshError(ctl, _("Invalid target argument"));
        return false;
1193 1194
    }

1195 1196 1197
    if (vshCommandOptLongLong(cmd, "duration", &duration) < 0) {
        vshError(ctl, _("Invalid duration argument"));
        return false;
1198
    }
1199

1200 1201 1202
    if (vshCommandOptUInt(cmd, "flags", &flags) < 0) {
        vshError(ctl, _("Invalid flags argument"));
        return false;
1203
    }
1204

1205 1206 1207 1208 1209 1210 1211 1212 1213
    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;
1214
    }
1215 1216 1217 1218

    if (duration <= 0) {
        vshError(ctl, "%s", _("Invalid duration"));
        return false;
1219 1220
    }

1221 1222 1223 1224
    if (virNodeSuspendForDuration(ctl->conn, suspendTarget, duration,
                                  flags) < 0) {
        vshError(ctl, "%s", _("The host was not suspended"));
        return false;
1225
    }
1226 1227
    return true;
}
1228

1229

1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
/*
 * "capabilities" command
 */
static const vshCmdInfo info_capabilities[] = {
    {"help", N_("capabilities")},
    {"desc", N_("Returns capabilities of hypervisor/driver.")},
    {NULL, NULL}
};

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

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

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

1254
    return true;
1255 1256
}

E
Eric Blake 已提交
1257
/*
1258
 * "nwfilter-define" command
E
Eric Blake 已提交
1259
 */
1260 1261 1262
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.")},
E
Eric Blake 已提交
1263 1264 1265
    {NULL, NULL}
};

1266 1267
static const vshCmdOptDef opts_nwfilter_define[] = {
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing an XML network filter description")},
E
Eric Blake 已提交
1268 1269 1270
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
1271
static bool
1272
cmdNWFilterDefine(vshControl *ctl, const vshCmd *cmd)
E
Eric Blake 已提交
1273
{
1274 1275 1276 1277
    virNWFilterPtr nwfilter;
    const char *from = NULL;
    bool ret = true;
    char *buffer;
E
Eric Blake 已提交
1278 1279

    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
1280
        return false;
E
Eric Blake 已提交
1281

1282
    if (vshCommandOptString(cmd, "file", &from) <= 0)
E
Eric Blake 已提交
1283
        return false;
E
Eric Blake 已提交
1284

1285 1286
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
        return false;
E
Eric Blake 已提交
1287

1288 1289
    nwfilter = virNWFilterDefineXML(ctl->conn, buffer);
    VIR_FREE(buffer);
E
Eric Blake 已提交
1290

1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
    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);
        ret = false;
    }
    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")},
E
Eric Blake 已提交
1314 1315 1316
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
1317
static bool
1318
cmdNWFilterUndefine(vshControl *ctl, const vshCmd *cmd)
E
Eric Blake 已提交
1319
{
1320
    virNWFilterPtr nwfilter;
E
Eric Blake 已提交
1321
    bool ret = true;
1322
    const char *name;
E
Eric Blake 已提交
1323 1324

    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
1325
        return false;
E
Eric Blake 已提交
1326

1327
    if (!(nwfilter = vshCommandOptNWFilter(ctl, cmd, &name)))
E
Eric Blake 已提交
1328
        return false;
E
Eric Blake 已提交
1329

1330 1331 1332 1333 1334
    if (virNWFilterUndefine(nwfilter) == 0) {
        vshPrint(ctl, _("Network filter %s undefined\n"), name);
    } else {
        vshError(ctl, _("Failed to undefine network filter %s"), name);
        ret = false;
E
Eric Blake 已提交
1335 1336
    }

1337
    virNWFilterFree(nwfilter);
E
Eric Blake 已提交
1338 1339 1340
    return ret;
}

1341

1342
/*
1343
 * "nwfilter-dumpxml" command
1344
 */
1345 1346 1347
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.")},
1348 1349 1350
    {NULL, NULL}
};

1351 1352
static const vshCmdOptDef opts_nwfilter_dumpxml[] = {
    {"nwfilter", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network filter name or uuid")},
1353 1354 1355
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
1356
static bool
1357
cmdNWFilterDumpXML(vshControl *ctl, const vshCmd *cmd)
1358
{
1359 1360 1361
    virNWFilterPtr nwfilter;
    bool ret = true;
    char *dump;
1362

1363
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
1364
        return false;
1365

1366
    if (!(nwfilter = vshCommandOptNWFilter(ctl, cmd, NULL)))
1367
        return false;
1368

1369 1370 1371 1372 1373 1374
    dump = virNWFilterGetXMLDesc(nwfilter, 0);
    if (dump != NULL) {
        vshPrint(ctl, "%s", dump);
        VIR_FREE(dump);
    } else {
        ret = false;
1375
    }
1376

1377 1378
    virNWFilterFree(nwfilter);
    return ret;
1379
}
1380

1381
/*
1382
 * "nwfilter-list" command
1383
 */
1384 1385 1386
static const vshCmdInfo info_nwfilter_list[] = {
    {"help", N_("list network filters")},
    {"desc", N_("Returns list of network filters.")},
1387 1388
    {NULL, NULL}
};
1389

1390
static const vshCmdOptDef opts_nwfilter_list[] = {
1391 1392
    {NULL, 0, 0, NULL}
};
1393

1394
static bool
1395
cmdNWFilterList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
1396
{
1397 1398
    int numfilters, i;
    char **names;
1399
    char uuid[VIR_UUID_STRING_BUFLEN];
1400

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

1404 1405 1406
    numfilters = virConnectNumOfNWFilters(ctl->conn);
    if (numfilters < 0) {
        vshError(ctl, "%s", _("Failed to list network filters"));
1407
        return false;
1408
    }
1409

1410
    names = vshMalloc(ctl, sizeof(char *) * numfilters);
1411

1412 1413 1414 1415 1416 1417
    if ((numfilters = virConnectListNWFilters(ctl->conn, names,
                                              numfilters)) < 0) {
        vshError(ctl, "%s", _("Failed to list network filters"));
        VIR_FREE(names);
        return false;
    }
1418

1419
    qsort(&names[0], numfilters, sizeof(char *), vshNameSorter);
1420

1421 1422 1423
    vshPrintExtra(ctl, "%-36s  %-20s \n", _("UUID"), _("Name"));
    vshPrintExtra(ctl,
       "----------------------------------------------------------------\n");
1424

1425 1426 1427
    for (i = 0; i < numfilters; i++) {
        virNWFilterPtr nwfilter =
            virNWFilterLookupByName(ctl->conn, names[i]);
1428

1429 1430 1431 1432
        /* this kind of work with networks is not atomic operation */
        if (!nwfilter) {
            VIR_FREE(names[i]);
            continue;
1433
        }
1434 1435 1436 1437 1438 1439 1440

        virNWFilterGetUUIDString(nwfilter, uuid);
        vshPrint(ctl, "%-36s  %-20s\n",
                 uuid,
                 virNWFilterGetName(nwfilter));
        virNWFilterFree(nwfilter);
        VIR_FREE(names[i]);
1441 1442
    }

1443 1444
    VIR_FREE(names);
    return true;
1445 1446
}

1447

G
Guido Günther 已提交
1448
/*
1449
 * "nwfilter-edit" command
G
Guido Günther 已提交
1450
 */
1451 1452 1453
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.")},
G
Guido Günther 已提交
1454 1455 1456
    {NULL, NULL}
};

1457 1458
static const vshCmdOptDef opts_nwfilter_edit[] = {
    {"nwfilter", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network filter name or uuid")},
G
Guido Günther 已提交
1459 1460 1461 1462
    {NULL, 0, 0, NULL}
};

static bool
1463
cmdNWFilterEdit(vshControl *ctl, const vshCmd *cmd)
G
Guido Günther 已提交
1464
{
1465 1466 1467
    bool ret = false;
    virNWFilterPtr nwfilter = NULL;
    virNWFilterPtr nwfilter_edited = NULL;
G
Guido Günther 已提交
1468 1469

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

1472 1473 1474
    nwfilter = vshCommandOptNWFilter(ctl, cmd, NULL);
    if (nwfilter == NULL)
        goto cleanup;
1475

1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
#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"
1488

1489 1490
    vshPrint(ctl, _("Network filter %s XML configuration edited.\n"),
             virNWFilterGetName(nwfilter_edited));
1491

1492
    ret = true;
1493

1494 1495 1496 1497 1498
cleanup:
    if (nwfilter)
        virNWFilterFree(nwfilter);
    if (nwfilter_edited)
        virNWFilterFree(nwfilter_edited);
1499

1500
    return ret;
1501 1502
}

1503
/*
1504
 * "nodedev-create" command
1505
 */
1506 1507 1508 1509 1510 1511
static const vshCmdInfo info_node_device_create[] = {
    {"help", N_("create a device defined "
                          "by an XML file on the node")},
    {"desc", N_("Create a device on the node.  Note that this "
                          "command creates devices on the physical host "
                          "that can then be assigned to a virtual machine.")},
1512 1513
    {NULL, NULL}
};
1514

1515 1516 1517
static const vshCmdOptDef opts_node_device_create[] = {
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ,
     N_("file containing an XML description of the device")},
1518 1519
    {NULL, 0, 0, NULL}
};
1520

1521
static bool
1522
cmdNodeDeviceCreate(vshControl *ctl, const vshCmd *cmd)
1523
{
1524 1525
    virNodeDevicePtr dev = NULL;
    const char *from = NULL;
1526
    bool ret = true;
1527
    char *buffer;
1528

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

1532 1533 1534 1535
    if (vshCommandOptString(cmd, "file", &from) <= 0)
        return false;

    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
1536 1537
        return false;

1538 1539 1540 1541 1542 1543 1544
    dev = virNodeDeviceCreateXML(ctl->conn, buffer, 0);
    VIR_FREE(buffer);

    if (dev != NULL) {
        vshPrint(ctl, _("Node device %s created from %s\n"),
                 virNodeDeviceGetName(dev), from);
        virNodeDeviceFree(dev);
1545
    } else {
1546
        vshError(ctl, _("Failed to create node device from %s"), from);
1547 1548
        ret = false;
    }
1549

1550 1551
    return ret;
}
1552

1553 1554

/*
1555
 * "nodedev-destroy" command
1556
 */
1557 1558 1559 1560
static const vshCmdInfo info_node_device_destroy[] = {
    {"help", N_("destroy (stop) a device on the node")},
    {"desc", N_("Destroy a device on the node.  Note that this "
                "command destroys devices on the physical host")},
1561 1562 1563
    {NULL, NULL}
};

1564 1565 1566
static const vshCmdOptDef opts_node_device_destroy[] = {
    {"name", VSH_OT_DATA, VSH_OFLAG_REQ,
     N_("name of the device to be destroyed")},
1567 1568 1569
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
1570
static bool
1571
cmdNodeDeviceDestroy(vshControl *ctl, const vshCmd *cmd)
1572
{
1573 1574 1575
    virNodeDevicePtr dev = NULL;
    bool ret = true;
    const char *name = NULL;
1576

1577
    if (!vshConnectionUsability(ctl, ctl->conn)) {
E
Eric Blake 已提交
1578
        return false;
1579
    }
1580

1581
    if (vshCommandOptString(cmd, "name", &name) <= 0)
E
Eric Blake 已提交
1582
        return false;
1583

1584
    dev = virNodeDeviceLookupByName(ctl->conn, name);
1585

1586 1587 1588 1589 1590 1591 1592 1593 1594
    if (virNodeDeviceDestroy(dev) == 0) {
        vshPrint(ctl, _("Destroyed node device '%s'\n"), name);
    } else {
        vshError(ctl, _("Failed to destroy node device '%s'"), name);
        ret = false;
    }

    virNodeDeviceFree(dev);
    return ret;
1595 1596
}

1597
/*
1598
 * "secret-define" command
1599
 */
1600 1601 1602
static const vshCmdInfo info_secret_define[] = {
    {"help", N_("define or modify a secret from an XML file")},
    {"desc", N_("Define or modify a secret.")},
1603 1604 1605
    {NULL, NULL}
};

1606 1607
static const vshCmdOptDef opts_secret_define[] = {
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing secret attributes in XML")},
1608 1609 1610
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
1611
static bool
1612
cmdSecretDefine(vshControl *ctl, const vshCmd *cmd)
1613
{
1614
    const char *from = NULL;
1615
    char *buffer;
1616 1617
    virSecretPtr res;
    char uuid[VIR_UUID_STRING_BUFLEN];
1618

1619
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
1620
        return false;
1621

1622
    if (vshCommandOptString(cmd, "file", &from) <= 0)
E
Eric Blake 已提交
1623
        return false;
1624

1625
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
E
Eric Blake 已提交
1626
        return false;
1627

1628
    res = virSecretDefineXML(ctl->conn, buffer, 0);
1629 1630
    VIR_FREE(buffer);

1631 1632 1633 1634 1635 1636 1637
    if (res == NULL) {
        vshError(ctl, _("Failed to set attributes from %s"), from);
        return false;
    }
    if (virSecretGetUUIDString(res, &(uuid[0])) < 0) {
        vshError(ctl, "%s", _("Failed to get UUID of created secret"));
        virSecretFree(res);
E
Eric Blake 已提交
1638
        return false;
1639
    }
1640 1641
    vshPrint(ctl, _("Secret %s created\n"), uuid);
    virSecretFree(res);
E
Eric Blake 已提交
1642
    return true;
1643 1644
}

1645
/*
1646
 * "secret-dumpxml" command
1647
 */
1648 1649 1650
static const vshCmdInfo info_secret_dumpxml[] = {
    {"help", N_("secret attributes in XML")},
    {"desc", N_("Output attributes of a secret as an XML dump to stdout.")},
1651 1652 1653
    {NULL, NULL}
};

1654 1655
static const vshCmdOptDef opts_secret_dumpxml[] = {
    {"secret", VSH_OT_DATA, VSH_OFLAG_REQ, N_("secret UUID")},
1656 1657 1658
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
1659
static bool
1660
cmdSecretDumpXML(vshControl *ctl, const vshCmd *cmd)
1661
{
1662 1663
    virSecretPtr secret;
    bool ret = false;
1664
    char *xml;
1665

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

1669 1670 1671
    secret = vshCommandOptSecret(ctl, cmd, NULL);
    if (secret == NULL)
        return false;
1672

1673 1674
    xml = virSecretGetXMLDesc(secret, 0);
    if (xml == NULL)
W
Wen Congyang 已提交
1675
        goto cleanup;
1676
    vshPrint(ctl, "%s", xml);
1677
    VIR_FREE(xml);
1678
    ret = true;
1679

1680 1681 1682
cleanup:
    virSecretFree(secret);
    return ret;
1683 1684 1685
}

/*
1686
 * "secret-set-value" command
1687
 */
1688 1689 1690
static const vshCmdInfo info_secret_set_value[] = {
    {"help", N_("set a secret value")},
    {"desc", N_("Set a secret value.")},
1691 1692 1693
    {NULL, NULL}
};

1694 1695 1696
static const vshCmdOptDef opts_secret_set_value[] = {
    {"secret", VSH_OT_DATA, VSH_OFLAG_REQ, N_("secret UUID")},
    {"base64", VSH_OT_DATA, VSH_OFLAG_REQ, N_("base64-encoded secret value")},
1697 1698 1699
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
1700
static bool
1701
cmdSecretSetValue(vshControl *ctl, const vshCmd *cmd)
1702
{
1703 1704 1705 1706 1707 1708
    virSecretPtr secret;
    size_t value_size;
    const char *base64 = NULL;
    char *value;
    int res;
    bool ret = false;
1709

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

1713 1714 1715
    secret = vshCommandOptSecret(ctl, cmd, NULL);
    if (secret == NULL)
        return false;
1716

1717
    if (vshCommandOptString(cmd, "base64", &base64) <= 0)
1718 1719
        goto cleanup;

1720 1721
    if (!base64_decode_alloc(base64, strlen(base64), &value, &value_size)) {
        vshError(ctl, "%s", _("Invalid base64 data"));
1722 1723
        goto cleanup;
    }
1724
    if (value == NULL) {
1725
        vshError(ctl, "%s", _("Failed to allocate memory"));
1726
        return false;
1727 1728
    }

1729 1730 1731
    res = virSecretSetValue(secret, (unsigned char *)value, value_size, 0);
    memset(value, 0, value_size);
    VIR_FREE(value);
J
Jim Fehlig 已提交
1732

1733 1734 1735
    if (res != 0) {
        vshError(ctl, "%s", _("Failed to set secret value"));
        goto cleanup;
1736
    }
1737 1738
    vshPrint(ctl, "%s", _("Secret value set\n"));
    ret = true;
1739

1740 1741 1742
cleanup:
    virSecretFree(secret);
    return ret;
1743 1744 1745
}

/*
1746
 * "secret-get-value" command
1747
 */
1748 1749 1750
static const vshCmdInfo info_secret_get_value[] = {
    {"help", N_("Output a secret value")},
    {"desc", N_("Output a secret value to stdout.")},
1751 1752 1753
    {NULL, NULL}
};

1754 1755
static const vshCmdOptDef opts_secret_get_value[] = {
    {"secret", VSH_OT_DATA, VSH_OFLAG_REQ, N_("secret UUID")},
1756 1757 1758
    {NULL, 0, 0, NULL}
};

1759 1760
static bool
cmdSecretGetValue(vshControl *ctl, const vshCmd *cmd)
1761
{
1762 1763 1764 1765 1766
    virSecretPtr secret;
    char *base64;
    unsigned char *value;
    size_t value_size;
    bool ret = false;
1767

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

1771 1772 1773
    secret = vshCommandOptSecret(ctl, cmd, NULL);
    if (secret == NULL)
        return false;
1774

1775 1776 1777
    value = virSecretGetValue(secret, &value_size, 0);
    if (value == NULL)
        goto cleanup;
1778

1779 1780 1781
    base64_encode_alloc((char *)value, value_size, &base64);
    memset(value, 0, value_size);
    VIR_FREE(value);
1782

1783 1784 1785 1786 1787 1788 1789 1790
    if (base64 == NULL) {
        vshError(ctl, "%s", _("Failed to allocate memory"));
        goto cleanup;
    }
    vshPrint(ctl, "%s", base64);
    memset(base64, 0, strlen(base64));
    VIR_FREE(base64);
    ret = true;
1791

1792 1793 1794
cleanup:
    virSecretFree(secret);
    return ret;
1795 1796
}

1797 1798
/*
 * "secret-undefine" command
1799
 */
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809
static const vshCmdInfo info_secret_undefine[] = {
    {"help", N_("undefine a secret")},
    {"desc", N_("Undefine a secret.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_secret_undefine[] = {
    {"secret", VSH_OT_DATA, VSH_OFLAG_REQ, N_("secret UUID")},
    {NULL, 0, 0, NULL}
};
1810

1811 1812
static bool
cmdSecretUndefine(vshControl *ctl, const vshCmd *cmd)
1813
{
1814 1815 1816
    virSecretPtr secret;
    bool ret = false;
    const char *uuid;
1817

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

1821 1822 1823
    secret = vshCommandOptSecret(ctl, cmd, &uuid);
    if (secret == NULL)
        return false;
1824

1825 1826 1827
    if (virSecretUndefine(secret) < 0) {
        vshError(ctl, _("Failed to delete secret %s"), uuid);
        goto cleanup;
1828
    }
1829 1830
    vshPrint(ctl, _("Secret %s deleted\n"), uuid);
    ret = true;
1831

1832 1833 1834
cleanup:
    virSecretFree(secret);
    return ret;
1835 1836
}

1837 1838 1839 1840 1841 1842 1843 1844 1845
/*
 * "secret-list" command
 */
static const vshCmdInfo info_secret_list[] = {
    {"help", N_("list secrets")},
    {"desc", N_("Returns a list of secrets")},
    {NULL, NULL}
};

E
Eric Blake 已提交
1846
static bool
1847
cmdSecretList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
1848
{
1849 1850
    int maxuuids = 0, i;
    char **uuids = NULL;
1851

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

1855 1856 1857 1858
    maxuuids = virConnectNumOfSecrets(ctl->conn);
    if (maxuuids < 0) {
        vshError(ctl, "%s", _("Failed to list secrets"));
        return false;
1859
    }
1860
    uuids = vshMalloc(ctl, sizeof(*uuids) * maxuuids);
1861

1862 1863 1864 1865 1866
    maxuuids = virConnectListSecrets(ctl->conn, uuids, maxuuids);
    if (maxuuids < 0) {
        vshError(ctl, "%s", _("Failed to list secrets"));
        VIR_FREE(uuids);
        return false;
1867 1868
    }

1869
    qsort(uuids, maxuuids, sizeof(char *), vshNameSorter);
1870

1871 1872
    vshPrintExtra(ctl, "%-36s %s\n", _("UUID"), _("Usage"));
    vshPrintExtra(ctl, "-----------------------------------------------------------\n");
1873

1874 1875 1876
    for (i = 0; i < maxuuids; i++) {
        virSecretPtr sec = virSecretLookupByUUIDString(ctl->conn, uuids[i]);
        const char *usageType = NULL;
1877

1878 1879 1880 1881
        if (!sec) {
            VIR_FREE(uuids[i]);
            continue;
        }
1882

1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
        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);
        VIR_FREE(uuids[i]);
1899
    }
1900 1901 1902
    VIR_FREE(uuids);
    return true;
}
1903 1904


1905 1906 1907 1908 1909 1910 1911 1912
/*
 * "version" command
 */
static const vshCmdInfo info_version[] = {
    {"help", N_("show version")},
    {"desc", N_("Display the system version information.")},
    {NULL, NULL}
};
1913

1914 1915 1916 1917
static const vshCmdOptDef opts_version[] = {
    {"daemon", VSH_OT_BOOL, VSH_OFLAG_NONE, N_("report daemon version too")},
    {NULL, 0, 0, NULL}
};
1918

1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
static bool
cmdVersion(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    unsigned long hvVersion;
    const char *hvType;
    unsigned long libVersion;
    unsigned long includeVersion;
    unsigned long apiVersion;
    unsigned long daemonVersion;
    int ret;
    unsigned int major;
    unsigned int minor;
    unsigned int rel;
1932

1933 1934 1935 1936 1937 1938 1939
    if (!vshConnectionUsability(ctl, ctl->conn))
        return false;

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

1942 1943 1944 1945 1946 1947 1948
    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);
1949

1950 1951 1952
    ret = virGetVersion(&libVersion, hvType, &apiVersion);
    if (ret < 0) {
        vshError(ctl, "%s", _("failed to get the library version"));
E
Eric Blake 已提交
1953
        return false;
1954
    }
1955 1956 1957 1958 1959 1960
    major = libVersion / 1000000;
    libVersion %= 1000000;
    minor = libVersion / 1000;
    rel = libVersion % 1000;
    vshPrint(ctl, _("Using library: libvir %d.%d.%d\n"),
             major, minor, rel);
1961

1962 1963 1964 1965 1966 1967
    major = apiVersion / 1000000;
    apiVersion %= 1000000;
    minor = apiVersion / 1000;
    rel = apiVersion % 1000;
    vshPrint(ctl, _("Using API: %s %d.%d.%d\n"), hvType,
             major, minor, rel);
1968

1969 1970 1971 1972
    ret = virConnectGetVersion(ctl->conn, &hvVersion);
    if (ret < 0) {
        vshError(ctl, "%s", _("failed to get the hypervisor version"));
        return false;
J
Jim Fehlig 已提交
1973
    }
1974 1975 1976 1977 1978 1979 1980 1981
    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;
1982

1983 1984 1985
        vshPrint(ctl, _("Running hypervisor: %s %d.%d.%d\n"),
                 hvType, major, minor, rel);
    }
1986

1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998
    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);
        }
J
Jim Fehlig 已提交
1999
    }
2000

2001
    return true;
2002 2003
}

2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
/* Tree listing helpers.  */

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

static int
vshTreePrintInternal(vshControl *ctl,
                     vshTreeLookup lookup,
                     void *opaque,
                     int num_devices,
                     int devid,
                     int lastdev,
                     bool root,
                     virBufferPtr indent)
2019
{
2020 2021 2022 2023
    int i;
    int nextlastdev = -1;
    int ret = -1;
    const char *dev = (lookup)(devid, false, opaque);
2024

2025
    if (virBufferError(indent))
2026 2027
        goto cleanup;

2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
    /* Print this device, with indent if not at root */
    vshPrint(ctl, "%s%s%s\n", virBufferCurrentContent(indent),
             root ? "" : "+- ", dev);

    /* Update indent to show '|' or ' ' for child devices */
    if (!root) {
        virBufferAddChar(indent, devid == lastdev ? ' ' : '|');
        virBufferAddChar(indent, ' ');
        if (virBufferError(indent))
            goto cleanup;
2038 2039
    }

2040 2041 2042
    /* Determine the index of the last child device */
    for (i = 0 ; i < num_devices ; i++) {
        const char *parent = (lookup)(i, true, opaque);
2043

2044 2045 2046
        if (parent && STREQ(parent, dev))
            nextlastdev = i;
    }
2047

2048 2049 2050
    /* If there is a child device, then print another blank line */
    if (nextlastdev != -1)
        vshPrint(ctl, "%s  |\n", virBufferCurrentContent(indent));
2051

2052 2053 2054 2055
    /* Finally print all children */
    virBufferAddLit(indent, "  ");
    for (i = 0 ; i < num_devices ; i++) {
        const char *parent = (lookup)(i, true, opaque);
2056

2057 2058 2059 2060 2061
        if (parent && STREQ(parent, dev) &&
            vshTreePrintInternal(ctl, lookup, opaque,
                                 num_devices, i, nextlastdev,
                                 false, indent) < 0)
            goto cleanup;
2062
    }
2063
    virBufferTrim(indent, "  ", -1);
2064

2065 2066 2067 2068
    /* If there was no child device, and we're the last in
     * a list of devices, then print another blank line */
    if (nextlastdev == -1 && devid == lastdev)
        vshPrint(ctl, "%s\n", virBufferCurrentContent(indent));
2069

2070 2071 2072
    if (!root)
        virBufferTrim(indent, NULL, 2);
    ret = 0;
2073 2074 2075 2076
cleanup:
    return ret;
}

2077 2078 2079
static int
vshTreePrint(vshControl *ctl, vshTreeLookup lookup, void *opaque,
             int num_devices, int devid)
2080
{
2081 2082
    int ret;
    virBuffer indent = VIR_BUFFER_INITIALIZER;
2083

2084 2085 2086 2087 2088
    ret = vshTreePrintInternal(ctl, lookup, opaque, num_devices,
                               devid, devid, true, &indent);
    if (ret < 0)
        vshError(ctl, "%s", _("Failed to complete tree listing"));
    virBufferFreeAndReset(&indent);
2089
    return ret;
2090
}
2091

2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
struct vshNodeList {
    char **names;
    char **parents;
};

static const char *
vshNodeListLookup(int devid, bool parent, void *opaque)
{
    struct vshNodeList *arrays = opaque;
    if (parent)
        return arrays->parents[devid];
    return arrays->names[devid];
2104 2105
}

2106
/*
2107
 * "nodedev-list" command
2108
 */
2109 2110 2111
static const vshCmdInfo info_node_list_devices[] = {
    {"help", N_("enumerate devices on this host")},
    {"desc", ""},
2112 2113 2114
    {NULL, NULL}
};

2115 2116 2117
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")},
2118 2119 2120
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
2121
static bool
2122
cmdNodeListDevices(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
2123
{
2124 2125 2126 2127 2128
    const char *cap = NULL;
    char **devices;
    int num_devices, i;
    bool tree = vshCommandOptBool(cmd, "tree");
    bool ret = true;
2129

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

2133 2134
    if (vshCommandOptString(cmd, "cap", &cap) <= 0)
        cap = NULL;
2135

2136 2137 2138 2139 2140 2141 2142
    num_devices = virNodeNumOfDevices(ctl->conn, cap, 0);
    if (num_devices < 0) {
        vshError(ctl, "%s", _("Failed to count node devices"));
        return false;
    } else if (num_devices == 0) {
        return true;
    }
2143

2144 2145 2146 2147 2148 2149 2150
    devices = vshMalloc(ctl, sizeof(char *) * num_devices);
    num_devices =
        virNodeListDevices(ctl->conn, cap, devices, num_devices, 0);
    if (num_devices < 0) {
        vshError(ctl, "%s", _("Failed to list node devices"));
        VIR_FREE(devices);
        return false;
J
Jim Fehlig 已提交
2151
    }
2152 2153 2154 2155
    qsort(&devices[0], num_devices, sizeof(char*), vshNameSorter);
    if (tree) {
        char **parents = vshMalloc(ctl, sizeof(char *) * num_devices);
        struct vshNodeList arrays = { devices, parents };
J
Jim Fehlig 已提交
2156

2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177
        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);
                parents[i] = parent ? vshStrdup(ctl, parent) : NULL;
            } else {
                parents[i] = NULL;
            }
            virNodeDeviceFree(dev);
        }
        for (i = 0 ; i < num_devices ; i++) {
            if (parents[i] == NULL &&
                vshTreePrint(ctl, vshNodeListLookup, &arrays, num_devices,
                             i) < 0)
                ret = false;
        }
        for (i = 0 ; i < num_devices ; i++) {
            VIR_FREE(devices[i]);
            VIR_FREE(parents[i]);
        }
        VIR_FREE(parents);
J
Jim Fehlig 已提交
2178
    } else {
2179 2180 2181 2182
        for (i = 0; i < num_devices; i++) {
            vshPrint(ctl, "%s\n", devices[i]);
            VIR_FREE(devices[i]);
        }
2183
    }
2184 2185
    VIR_FREE(devices);
    return ret;
2186 2187
}

O
Osier Yang 已提交
2188
/*
2189
 * "nodedev-dumpxml" command
O
Osier Yang 已提交
2190
 */
2191 2192 2193
static const vshCmdInfo info_node_device_dumpxml[] = {
    {"help", N_("node device details in XML")},
    {"desc", N_("Output the node device details as an XML dump to stdout.")},
O
Osier Yang 已提交
2194 2195 2196
    {NULL, NULL}
};

2197 2198 2199

static const vshCmdOptDef opts_node_device_dumpxml[] = {
    {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("device key")},
O
Osier Yang 已提交
2200 2201 2202 2203
    {NULL, 0, 0, NULL}
};

static bool
2204
cmdNodeDeviceDumpXML(vshControl *ctl, const vshCmd *cmd)
O
Osier Yang 已提交
2205
{
2206 2207 2208
    const char *name = NULL;
    virNodeDevicePtr device;
    char *xml;
O
Osier Yang 已提交
2209

2210 2211 2212 2213 2214 2215 2216
    if (!vshConnectionUsability(ctl, ctl->conn))
        return false;
    if (vshCommandOptString(cmd, "device", &name) <= 0)
        return false;
    if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) {
        vshError(ctl, "%s '%s'", _("Could not find matching device"), name);
        return false;
O
Osier Yang 已提交
2217 2218
    }

2219 2220 2221 2222
    xml = virNodeDeviceGetXMLDesc(device, 0);
    if (!xml) {
        virNodeDeviceFree(device);
        return false;
O
Osier Yang 已提交
2223 2224
    }

2225 2226 2227 2228 2229
    vshPrint(ctl, "%s\n", xml);
    VIR_FREE(xml);
    virNodeDeviceFree(device);
    return true;
}
O
Osier Yang 已提交
2230

2231 2232 2233 2234 2235 2236 2237 2238
/*
 * "nodedev-detach" command
 */
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.")},
    {NULL, NULL}
};
O
Osier Yang 已提交
2239 2240


2241 2242 2243 2244
static const vshCmdOptDef opts_node_device_detach[] = {
    {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("device key")},
    {NULL, 0, 0, NULL}
};
O
Osier Yang 已提交
2245

2246 2247 2248 2249 2250 2251
static bool
cmdNodeDeviceDetach(vshControl *ctl, const vshCmd *cmd)
{
    const char *name = NULL;
    virNodeDevicePtr device;
    bool ret = true;
O
Osier Yang 已提交
2252

2253 2254 2255 2256 2257 2258 2259
    if (!vshConnectionUsability(ctl, ctl->conn))
        return false;
    if (vshCommandOptString(cmd, "device", &name) <= 0)
        return false;
    if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) {
        vshError(ctl, "%s '%s'", _("Could not find matching device"), name);
        return false;
O
Osier Yang 已提交
2260 2261
    }

2262 2263 2264 2265 2266 2267 2268 2269 2270
    /* Yes, our public API is misspelled.  At least virsh can accept
     * either spelling.  */
    if (virNodeDeviceDettach(device) == 0) {
        vshPrint(ctl, _("Device %s detached\n"), name);
    } else {
        vshError(ctl, _("Failed to detach device %s"), name);
        ret = false;
    }
    virNodeDeviceFree(device);
O
Osier Yang 已提交
2271 2272 2273
    return ret;
}

2274
/*
2275
 * "nodedev-reattach" command
2276
 */
2277 2278 2279
static const vshCmdInfo info_node_device_reattach[] = {
    {"help", N_("reattach node device to its device driver")},
    {"desc", N_("Reattach node device to its device driver once released by the domain.")},
2280 2281 2282
    {NULL, NULL}
};

2283 2284 2285

static const vshCmdOptDef opts_node_device_reattach[] = {
    {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("device key")},
2286 2287 2288
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
2289
static bool
2290
cmdNodeDeviceReAttach(vshControl *ctl, const vshCmd *cmd)
2291
{
2292 2293 2294
    const char *name = NULL;
    virNodeDevicePtr device;
    bool ret = true;
2295

2296
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
2297
        return false;
2298
    if (vshCommandOptString(cmd, "device", &name) <= 0)
E
Eric Blake 已提交
2299
        return false;
2300 2301
    if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) {
        vshError(ctl, "%s '%s'", _("Could not find matching device"), name);
E
Eric Blake 已提交
2302
        return false;
2303
    }
2304

2305 2306
    if (virNodeDeviceReAttach(device) == 0) {
        vshPrint(ctl, _("Device %s re-attached\n"), name);
2307
    } else {
2308 2309
        vshError(ctl, _("Failed to re-attach device %s"), name);
        ret = false;
2310
    }
2311 2312 2313
    virNodeDeviceFree(device);
    return ret;
}
2314

2315 2316 2317 2318 2319 2320 2321 2322
/*
 * "nodedev-reset" command
 */
static const vshCmdInfo info_node_device_reset[] = {
    {"help", N_("reset node device")},
    {"desc", N_("Reset node device before or after assigning to a domain.")},
    {NULL, NULL}
};
2323 2324


2325 2326 2327 2328
static const vshCmdOptDef opts_node_device_reset[] = {
    {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("device key")},
    {NULL, 0, 0, NULL}
};
2329

2330 2331 2332 2333 2334 2335
static bool
cmdNodeDeviceReset(vshControl *ctl, const vshCmd *cmd)
{
    const char *name = NULL;
    virNodeDevicePtr device;
    bool ret = true;
2336

2337 2338 2339 2340 2341 2342 2343
    if (!vshConnectionUsability(ctl, ctl->conn))
        return false;
    if (vshCommandOptString(cmd, "device", &name) <= 0)
        return false;
    if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) {
        vshError(ctl, "%s '%s'", _("Could not find matching device"), name);
        return false;
2344 2345
    }

2346 2347 2348 2349 2350 2351 2352
    if (virNodeDeviceReset(device) == 0) {
        vshPrint(ctl, _("Device %s reset\n"), name);
    } else {
        vshError(ctl, _("Failed to reset device %s"), name);
        ret = false;
    }
    virNodeDeviceFree(device);
2353 2354 2355
    return ret;
}

2356
/*
2357
 * "hostname" command
2358
 */
2359 2360 2361
static const vshCmdInfo info_hostname[] = {
    {"help", N_("print the hypervisor hostname")},
    {"desc", ""},
2362 2363 2364
    {NULL, NULL}
};

E
Eric Blake 已提交
2365
static bool
2366
cmdHostname(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
2367
{
2368
    char *hostname;
2369

2370
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
2371
        return false;
2372

2373 2374 2375
    hostname = virConnectGetHostname(ctl->conn);
    if (hostname == NULL) {
        vshError(ctl, "%s", _("failed to get hostname"));
E
Eric Blake 已提交
2376
        return false;
2377
    }
2378

2379 2380
    vshPrint (ctl, "%s\n", hostname);
    VIR_FREE(hostname);
2381

2382 2383
    return true;
}
2384

2385 2386 2387 2388 2389 2390 2391 2392
/*
 * "uri" command
 */
static const vshCmdInfo info_uri[] = {
    {"help", N_("print the hypervisor canonical URI")},
    {"desc", ""},
    {NULL, NULL}
};
2393

2394 2395 2396 2397
static bool
cmdURI(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    char *uri;
2398

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

2402 2403 2404 2405
    uri = virConnectGetURI(ctl->conn);
    if (uri == NULL) {
        vshError(ctl, "%s", _("failed to get URI"));
        return false;
2406 2407
    }

2408 2409
    vshPrint(ctl, "%s\n", uri);
    VIR_FREE(uri);
2410

2411 2412
    return true;
}
2413

2414 2415 2416 2417 2418 2419 2420 2421 2422
/*
 * "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}
};
2423

2424 2425 2426 2427
static bool
cmdSysinfo(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    char *sysinfo;
2428

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

2432 2433 2434 2435
    sysinfo = virConnectGetSysinfo(ctl->conn, 0);
    if (sysinfo == NULL) {
        vshError(ctl, "%s", _("failed to get sysinfo"));
        return false;
2436 2437
    }

2438 2439
    vshPrint(ctl, "%s", sysinfo);
    VIR_FREE(sysinfo);
2440

2441
    return true;
2442 2443
}

2444 2445
/* Common code for the edit / net-edit / pool-edit functions which follow. */
static char *
2446
editWriteToTempFile(vshControl *ctl, const char *doc)
2447 2448 2449 2450 2451 2452 2453
{
    char *ret;
    const char *tmpdir;
    int fd;

    tmpdir = getenv ("TMPDIR");
    if (!tmpdir) tmpdir = "/tmp";
2454 2455 2456 2457
    if (virAsprintf(&ret, "%s/virshXXXXXX.xml", tmpdir) < 0) {
        vshError(ctl, "%s", _("out of memory"));
        return NULL;
    }
2458
    fd = mkstemps(ret, 4);
2459
    if (fd == -1) {
2460
        vshError(ctl, _("mkstemps: failed to create temporary file: %s"),
2461
                 strerror(errno));
2462
        VIR_FREE(ret);
2463 2464 2465
        return NULL;
    }

2466
    if (safewrite(fd, doc, strlen(doc)) == -1) {
2467 2468
        vshError(ctl, _("write: %s: failed to write to temporary file: %s"),
                 ret, strerror(errno));
S
Stefan Berger 已提交
2469
        VIR_FORCE_CLOSE(fd);
2470
        unlink(ret);
2471
        VIR_FREE(ret);
2472 2473
        return NULL;
    }
S
Stefan Berger 已提交
2474
    if (VIR_CLOSE(fd) < 0) {
2475 2476
        vshError(ctl, _("close: %s: failed to write or close temporary file: %s"),
                 ret, strerror(errno));
2477
        unlink(ret);
2478
        VIR_FREE(ret);
2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490
        return NULL;
    }

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

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

static int
2491
editFile(vshControl *ctl, const char *filename)
2492 2493
{
    const char *editor;
E
Eric Blake 已提交
2494 2495 2496 2497
    virCommandPtr cmd;
    int ret = -1;
    int outfd = STDOUT_FILENO;
    int errfd = STDERR_FILENO;
2498

2499
    editor = getenv("VISUAL");
E
Eric Blake 已提交
2500
    if (!editor)
2501
        editor = getenv("EDITOR");
E
Eric Blake 已提交
2502 2503
    if (!editor)
        editor = "vi"; /* could be cruel & default to ed(1) here */
2504

2505 2506 2507 2508 2509
    /* 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 已提交
2510 2511
     * is why sudo scrubs it by default).  Conversely, if the editor
     * is safe, we can run it directly rather than wasting a shell.
2512
     */
2513 2514
    if (strspn(editor, ACCEPTED_CHARS) != strlen(editor)) {
        if (strspn(filename, ACCEPTED_CHARS) != strlen(filename)) {
E
Eric Blake 已提交
2515 2516 2517 2518 2519 2520 2521 2522 2523 2524
            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);
2525 2526
    }

E
Eric Blake 已提交
2527 2528 2529 2530 2531 2532 2533
    virCommandSetInputFD(cmd, STDIN_FILENO);
    virCommandSetOutputFD(cmd, &outfd);
    virCommandSetErrorFD(cmd, &errfd);
    if (virCommandRunAsync(cmd, NULL) < 0 ||
        virCommandWait(cmd, NULL) < 0) {
        virshReportError(ctl);
        goto cleanup;
2534
    }
E
Eric Blake 已提交
2535
    ret = 0;
2536

E
Eric Blake 已提交
2537 2538 2539
cleanup:
    virCommandFree(cmd);
    return ret;
2540 2541 2542
}

static char *
2543
editReadBackFile(vshControl *ctl, const char *filename)
2544 2545 2546
{
    char *ret;

E
Eric Blake 已提交
2547
    if (virFileReadAll(filename, VIRSH_MAX_XML_FILE, &ret) == -1) {
2548
        vshError(ctl,
2549
                 _("%s: failed to read temporary file: %s"),
2550
                 filename, strerror(errno));
2551 2552 2553 2554 2555
        return NULL;
    }
    return ret;
}

2556

P
Paolo Bonzini 已提交
2557 2558 2559 2560
/*
 * "cd" command
 */
static const vshCmdInfo info_cd[] = {
2561 2562
    {"help", N_("change the current directory")},
    {"desc", N_("Change the current directory.")},
P
Paolo Bonzini 已提交
2563 2564 2565 2566
    {NULL, NULL}
};

static const vshCmdOptDef opts_cd[] = {
2567
    {"dir", VSH_OT_DATA, 0, N_("directory to switch to (default: home or else root)")},
P
Paolo Bonzini 已提交
2568 2569 2570
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
2571
static bool
2572
cmdCd(vshControl *ctl, const vshCmd *cmd)
P
Paolo Bonzini 已提交
2573
{
2574
    const char *dir = NULL;
2575
    char *dir_malloced = NULL;
E
Eric Blake 已提交
2576
    bool ret = true;
P
Paolo Bonzini 已提交
2577 2578

    if (!ctl->imode) {
2579
        vshError(ctl, "%s", _("cd: command valid only in interactive mode"));
E
Eric Blake 已提交
2580
        return false;
P
Paolo Bonzini 已提交
2581 2582
    }

2583
    if (vshCommandOptString(cmd, "dir", &dir) <= 0) {
2584
        dir = dir_malloced = virGetUserDirectory();
P
Paolo Bonzini 已提交
2585 2586 2587 2588
    }
    if (!dir)
        dir = "/";

P
Phil Petty 已提交
2589
    if (chdir(dir) == -1) {
2590
        vshError(ctl, _("cd: %s: %s"), strerror(errno), dir);
E
Eric Blake 已提交
2591
        ret = false;
P
Paolo Bonzini 已提交
2592 2593
    }

2594
    VIR_FREE(dir_malloced);
P
Phil Petty 已提交
2595
    return ret;
P
Paolo Bonzini 已提交
2596 2597 2598 2599 2600 2601
}

/*
 * "pwd" command
 */
static const vshCmdInfo info_pwd[] = {
2602 2603
    {"help", N_("print the current directory")},
    {"desc", N_("Print the current directory.")},
P
Paolo Bonzini 已提交
2604 2605 2606
    {NULL, NULL}
};

E
Eric Blake 已提交
2607
static bool
P
Paolo Bonzini 已提交
2608 2609 2610
cmdPwd(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    char *cwd;
2611
    bool ret = true;
P
Paolo Bonzini 已提交
2612

2613 2614
    cwd = getcwd(NULL, 0);
    if (!cwd) {
2615 2616
        vshError(ctl, _("pwd: cannot get current directory: %s"),
                 strerror(errno));
2617 2618
        ret = false;
    } else {
2619
        vshPrint(ctl, _("%s\n"), cwd);
2620 2621
        VIR_FREE(cwd);
    }
P
Paolo Bonzini 已提交
2622

2623
    return ret;
P
Paolo Bonzini 已提交
2624 2625
}

E
Eric Blake 已提交
2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637
/*
 * "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 已提交
2638
    {"str", VSH_OT_ALIAS, 0, "string"},
2639
    {"string", VSH_OT_ARGV, 0, N_("arguments to echo")},
E
Eric Blake 已提交
2640 2641 2642 2643 2644 2645
    {NULL, 0, 0, NULL}
};

/* Exists mainly for debugging virsh, but also handy for adding back
 * quotes for later evaluation.
 */
E
Eric Blake 已提交
2646
static bool
2647
cmdEcho(vshControl *ctl, const vshCmd *cmd)
E
Eric Blake 已提交
2648 2649 2650 2651
{
    bool shell = false;
    bool xml = false;
    int count = 0;
2652
    const vshCmdOpt *opt = NULL;
E
Eric Blake 已提交
2653 2654 2655 2656 2657 2658 2659 2660
    char *arg;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    if (vshCommandOptBool(cmd, "shell"))
        shell = true;
    if (vshCommandOptBool(cmd, "xml"))
        xml = true;

2661
    while ((opt = vshCommandOptArgv(cmd, opt))) {
2662 2663
        char *str;
        virBuffer xmlbuf = VIR_BUFFER_INITIALIZER;
E
Eric Blake 已提交
2664

2665
        arg = opt->data;
2666

E
Eric Blake 已提交
2667 2668
        if (count)
            virBufferAddChar(&buf, ' ');
2669

E
Eric Blake 已提交
2670
        if (xml) {
2671 2672 2673 2674
            virBufferEscapeString(&xmlbuf, "%s", arg);
            if (virBufferError(&buf)) {
                vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
                return false;
E
Eric Blake 已提交
2675
            }
2676 2677 2678
            str = virBufferContentAndReset(&xmlbuf);
        } else {
            str = vshStrdup(ctl, arg);
E
Eric Blake 已提交
2679
        }
2680 2681 2682 2683 2684

        if (shell)
            virBufferEscapeShell(&buf, str);
        else
            virBufferAdd(&buf, str, -1);
E
Eric Blake 已提交
2685
        count++;
2686
        VIR_FREE(str);
E
Eric Blake 已提交
2687 2688 2689 2690
    }

    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
E
Eric Blake 已提交
2691
        return false;
E
Eric Blake 已提交
2692 2693 2694 2695 2696
    }
    arg = virBufferContentAndReset(&buf);
    if (arg)
        vshPrint(ctl, "%s", arg);
    VIR_FREE(arg);
E
Eric Blake 已提交
2697
    return true;
E
Eric Blake 已提交
2698 2699
}

K
Karel Zak 已提交
2700 2701 2702
/*
 * "quit" command
 */
2703
static const vshCmdInfo info_quit[] = {
2704
    {"help", N_("quit this interactive terminal")},
2705
    {"desc", ""},
2706
    {NULL, NULL}
K
Karel Zak 已提交
2707 2708
};

E
Eric Blake 已提交
2709
static bool
2710
cmdQuit(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
2711
{
E
Eric Blake 已提交
2712 2713
    ctl->imode = false;
    return true;
K
Karel Zak 已提交
2714 2715
}

2716 2717 2718 2719 2720 2721 2722
/* 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;
2723
    bool halt = false;
2724 2725 2726
    char *doc = NULL;
    xmlDocPtr xml = NULL;
    xmlXPathContextPtr ctxt = NULL;
E
Eric Blake 已提交
2727
    const char *name = NULL;
2728 2729

    snapshot = virDomainSnapshotCreateXML(dom, buffer, flags);
2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753

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

2754 2755 2756
    if (snapshot == NULL)
        goto cleanup;

2757 2758 2759 2760 2761
    if (halt && virDomainDestroy(dom) < 0) {
        virshReportError(ctl);
        goto cleanup;
    }

E
Eric Blake 已提交
2762
    name = virDomainSnapshotGetName(snapshot);
2763
    if (!name) {
E
Eric Blake 已提交
2764
        vshError(ctl, "%s", _("Could not get snapshot name"));
2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783
        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;
}

2784 2785 2786 2787
/*
 * "snapshot-create" command
 */
static const vshCmdInfo info_snapshot_create[] = {
E
Eric Blake 已提交
2788 2789
    {"help", N_("Create a snapshot from XML")},
    {"desc", N_("Create a snapshot (disk and RAM) from XML")},
2790 2791 2792 2793 2794 2795
    {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")},
2796 2797 2798
    {"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")},
2799
    {"halt", VSH_OT_BOOL, 0, N_("halt domain after snapshot is created")},
2800
    {"disk-only", VSH_OT_BOOL, 0, N_("capture disk state but not vm state")},
2801
    {"reuse-external", VSH_OT_BOOL, 0, N_("reuse any existing external files")},
2802
    {"quiesce", VSH_OT_BOOL, 0, N_("quiesce guest's file systems")},
E
Eric Blake 已提交
2803
    {"atomic", VSH_OT_BOOL, 0, N_("require atomic operation")},
2804 2805 2806
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
2807
static bool
2808 2809 2810
cmdSnapshotCreate(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
E
Eric Blake 已提交
2811
    bool ret = false;
2812
    const char *from = NULL;
2813
    char *buffer = NULL;
2814 2815 2816 2817 2818 2819 2820 2821
    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;
2822 2823
    if (vshCommandOptBool(cmd, "halt"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_HALT;
2824 2825
    if (vshCommandOptBool(cmd, "disk-only"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY;
2826 2827
    if (vshCommandOptBool(cmd, "reuse-external"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT;
2828 2829
    if (vshCommandOptBool(cmd, "quiesce"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE;
E
Eric Blake 已提交
2830 2831
    if (vshCommandOptBool(cmd, "atomic"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC;
2832

2833
    if (!vshConnectionUsability(ctl, ctl->conn))
2834 2835 2836 2837 2838 2839
        goto cleanup;

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

2840
    if (vshCommandOptString(cmd, "xmlfile", &from) <= 0)
E
Eric Blake 已提交
2841
        buffer = vshStrdup(ctl, "<domainsnapshot/>");
2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856
    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;
    }

2857
    ret = vshSnapshotCreate(ctl, dom, buffer, flags, from);
2858 2859 2860 2861 2862 2863 2864 2865 2866

cleanup:
    VIR_FREE(buffer);
    if (dom)
        virDomainFree(dom);

    return ret;
}

2867 2868 2869
/*
 * "snapshot-create-as" command
 */
2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887
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 */
2888
            memmove(&tmp[1], &tmp[2], len - (tmp - spec) - 2 + 1);
2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925
            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;
}

2926 2927 2928 2929 2930 2931 2932 2933 2934 2935
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 已提交
2936
    {"print-xml", VSH_OT_BOOL, 0, N_("print XML document rather than create")},
2937
    {"no-metadata", VSH_OT_BOOL, 0, N_("take snapshot but create no metadata")},
2938
    {"halt", VSH_OT_BOOL, 0, N_("halt domain after snapshot is created")},
2939
    {"disk-only", VSH_OT_BOOL, 0, N_("capture disk state but not vm state")},
2940
    {"reuse-external", VSH_OT_BOOL, 0, N_("reuse any existing external files")},
2941
    {"quiesce", VSH_OT_BOOL, 0, N_("quiesce guest's file systems")},
E
Eric Blake 已提交
2942
    {"atomic", VSH_OT_BOOL, 0, N_("require atomic operation")},
2943 2944
    {"diskspec", VSH_OT_ARGV, 0,
     N_("disk attributes: disk[,snapshot=type][,driver=type][,file=name]")},
2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956
    {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;
2957
    unsigned int flags = 0;
2958
    const vshCmdOpt *opt = NULL;
2959 2960 2961

    if (vshCommandOptBool(cmd, "no-metadata"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA;
2962 2963
    if (vshCommandOptBool(cmd, "halt"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_HALT;
2964 2965
    if (vshCommandOptBool(cmd, "disk-only"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY;
2966 2967
    if (vshCommandOptBool(cmd, "reuse-external"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT;
2968 2969
    if (vshCommandOptBool(cmd, "quiesce"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE;
E
Eric Blake 已提交
2970 2971
    if (vshCommandOptBool(cmd, "atomic"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC;
2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987

    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)
2988
        virBufferEscapeString(&buf, "  <name>%s</name>\n", name);
2989
    if (desc)
2990
        virBufferEscapeString(&buf, "  <description>%s</description>\n", desc);
2991 2992 2993 2994 2995 2996 2997 2998 2999 3000
    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");
    }
3001 3002 3003 3004 3005 3006 3007 3008
    virBufferAddLit(&buf, "</domainsnapshot>\n");

    buffer = virBufferContentAndReset(&buf);
    if (buffer == NULL) {
        vshError(ctl, "%s", _("Out of memory"));
        goto cleanup;
    }

E
Eric Blake 已提交
3009 3010 3011 3012 3013 3014
    if (vshCommandOptBool(cmd, "print-xml")) {
        vshPrint(ctl, "%s\n",  buffer);
        ret = true;
        goto cleanup;
    }

3015
    ret = vshSnapshotCreate(ctl, dom, buffer, flags, NULL);
3016 3017 3018 3019 3020 3021 3022 3023 3024

cleanup:
    VIR_FREE(buffer);
    if (dom)
        virDomainFree(dom);

    return ret;
}

3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063
/* 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;
}

3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074
/*
 * "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")},
3075
    {"snapshotname", VSH_OT_DATA, 0, N_("snapshot name")},
3076
    {"current", VSH_OT_BOOL, 0, N_("also set edited snapshot as current")},
3077 3078
    {"rename", VSH_OT_BOOL, 0, N_("allow renaming an existing snapshot")},
    {"clone", VSH_OT_BOOL, 0, N_("allow cloning to new name")},
3079 3080 3081 3082 3083 3084 3085 3086
    {NULL, 0, 0, NULL}
};

static bool
cmdSnapshotEdit(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
    virDomainSnapshotPtr snapshot = NULL;
3087
    virDomainSnapshotPtr edited = NULL;
3088
    const char *name;
3089
    const char *edited_name;
3090 3091 3092
    bool ret = false;
    unsigned int getxml_flags = VIR_DOMAIN_XML_SECURE;
    unsigned int define_flags = VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE;
3093 3094 3095 3096 3097 3098 3099 3100
    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;
    }
3101

3102 3103
    if (vshCommandOptBool(cmd, "current") &&
        vshCommandOptBool(cmd, "snapshotname"))
3104 3105 3106 3107 3108 3109 3110 3111 3112
        define_flags |= VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT;

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

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

3113 3114
    if (vshLookupSnapshot(ctl, cmd, "snapshotname", false, dom,
                          &snapshot, &name) < 0)
3115 3116
        goto cleanup;

W
Wen Congyang 已提交
3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135
#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"
3136

3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160
    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;
        }
    }

3161 3162 3163
    ret = true;

cleanup:
3164 3165
    if (edited)
        virDomainSnapshotFree(edited);
3166 3167 3168 3169
    else
        vshError(ctl, _("Failed to update %s"), name);
    if (snapshot)
        virDomainSnapshotFree(snapshot);
3170 3171 3172 3173 3174
    if (dom)
        virDomainFree(dom);
    return ret;
}

3175 3176 3177 3178
/*
 * "snapshot-current" command
 */
static const vshCmdInfo info_snapshot_current[] = {
3179 3180
    {"help", N_("Get or set the current snapshot")},
    {"desc", N_("Get or set the current snapshot")},
3181 3182 3183 3184 3185
    {NULL, NULL}
};

static const vshCmdOptDef opts_snapshot_current[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
3186
    {"name", VSH_OT_BOOL, 0, N_("list the name, rather than the full xml")},
3187 3188
    {"security-info", VSH_OT_BOOL, 0,
     N_("include security sensitive information in XML dump")},
3189 3190
    {"snapshotname", VSH_OT_DATA, 0,
     N_("name of existing snapshot to make current")},
3191 3192 3193
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
3194
static bool
3195 3196 3197
cmdSnapshotCurrent(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
E
Eric Blake 已提交
3198
    bool ret = false;
3199 3200
    int current;
    virDomainSnapshotPtr snapshot = NULL;
3201
    char *xml = NULL;
3202
    const char *snapshotname = NULL;
3203
    unsigned int flags = 0;
3204
    const char *domname;
3205 3206 3207

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

3209
    if (!vshConnectionUsability(ctl, ctl->conn))
3210 3211
        goto cleanup;

3212
    dom = vshCommandOptDomain(ctl, cmd, &domname);
3213 3214 3215
    if (dom == NULL)
        goto cleanup;

3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235
    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;
3236 3237 3238
        /* 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;
3239 3240 3241 3242 3243 3244 3245 3246 3247
        snapshot2 = virDomainSnapshotCreateXML(dom, xml, flags);
        if (snapshot2 == NULL)
            goto cleanup;
        virDomainSnapshotFree(snapshot2);
        vshPrint(ctl, _("Snapshot %s set as current"), snapshotname);
        ret = true;
        goto cleanup;
    }

3248
    current = virDomainHasCurrentSnapshot(dom, 0);
3249 3250 3251 3252
    if (current < 0) {
        goto cleanup;
    } else if (!current) {
        vshError(ctl, _("domain '%s' has no current snapshot"), domname);
3253
        goto cleanup;
3254
    } else {
E
Eric Blake 已提交
3255
        const char *name = NULL;
3256 3257 3258 3259

        if (!(snapshot = virDomainSnapshotCurrent(dom, 0)))
            goto cleanup;

3260
        if (vshCommandOptBool(cmd, "name")) {
E
Eric Blake 已提交
3261
            name = virDomainSnapshotGetName(snapshot);
3262 3263
            if (!name)
                goto cleanup;
E
Eric Blake 已提交
3264 3265 3266 3267
        } else {
            xml = virDomainSnapshotGetXMLDesc(snapshot, flags);
            if (!xml)
                goto cleanup;
3268 3269 3270
        }

        vshPrint(ctl, "%s", name ? name : xml);
3271 3272
    }

E
Eric Blake 已提交
3273
    ret = true;
3274 3275

cleanup:
3276 3277
    if (!ret)
        virshReportError(ctl);
3278
    VIR_FREE(xml);
3279 3280 3281 3282 3283 3284 3285 3286
    if (snapshot)
        virDomainSnapshotFree(snapshot);
    if (dom)
        virDomainFree(dom);

    return ret;
}

3287
/* Helper function to get the name of a snapshot's parent.  Caller
3288 3289 3290 3291 3292 3293
 * 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)
3294 3295 3296 3297 3298
{
    virDomainSnapshotPtr parent = NULL;
    char *xml = NULL;
    xmlDocPtr xmldoc = NULL;
    xmlXPathContextPtr ctxt = NULL;
3299 3300 3301
    int ret = -1;

    *parent_name = NULL;
3302 3303

    /* Try new API, since it is faster. */
3304
    if (!ctl->useSnapshotOld) {
3305 3306 3307
        parent = virDomainSnapshotGetParent(snapshot, 0);
        if (parent) {
            /* API works, and virDomainSnapshotGetName will succeed */
3308 3309
            *parent_name = vshStrdup(ctl, virDomainSnapshotGetName(parent));
            ret = 0;
3310 3311 3312 3313
            goto cleanup;
        }
        if (last_error->code == VIR_ERR_NO_DOMAIN_SNAPSHOT) {
            /* API works, and we found a root with no parent */
3314
            ret = 0;
3315 3316 3317
            goto cleanup;
        }
        /* API didn't work, fall back to XML scraping. */
3318
        ctl->useSnapshotOld = true;
3319 3320 3321 3322 3323 3324 3325 3326 3327 3328
    }

    xml = virDomainSnapshotGetXMLDesc(snapshot, 0);
    if (!xml)
        goto cleanup;

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

3329 3330
    *parent_name = virXPathString("string(/domainsnapshot/parent/name)", ctxt);
    ret = 0;
3331 3332

cleanup:
3333 3334 3335 3336 3337 3338 3339
    if (ret < 0) {
        virshReportError(ctl);
        vshError(ctl, "%s", _("unable to determine if snapshot has parent"));
    } else {
        virFreeError(last_error);
        last_error = NULL;
    }
3340 3341 3342 3343 3344
    if (parent)
        virDomainSnapshotFree(parent);
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xmldoc);
    VIR_FREE(xml);
3345
    return ret;
3346 3347
}

E
Eric Blake 已提交
3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470
/*
 * "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;
}

3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519
/* 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.  */
3520
static vshSnapshotListPtr
3521 3522 3523 3524 3525 3526 3527 3528 3529
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;
3530
    virDomainSnapshotPtr *snaps;
3531 3532 3533 3534 3535 3536
    vshSnapshotListPtr snaplist = vshMalloc(ctl, sizeof(*snaplist));
    vshSnapshotListPtr ret = NULL;
    const char *fromname = NULL;
    int start_index = -1;
    int deleted = 0;

3537 3538 3539 3540 3541 3542 3543 3544 3545 3546
    /* 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.  */
3547 3548
        snaplist->snaps = vshCalloc(ctl, count + (tree && from),
                                    sizeof(*snaplist->snaps));
3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565
        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;
    }
3566

E
Eric Blake 已提交
3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590
    /* 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;
    }

3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 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 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801
    /* 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;
}

3802 3803 3804 3805 3806 3807 3808 3809 3810
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);
}

3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821
/*
 * "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")},
3822
    {"parent", VSH_OT_BOOL, 0, N_("add a column showing parent snapshot")},
3823
    {"roots", VSH_OT_BOOL, 0, N_("list only snapshots without parents")},
3824
    {"leaves", VSH_OT_BOOL, 0, N_("list only snapshots without children")},
E
Eric Blake 已提交
3825 3826
    {"no-leaves", VSH_OT_BOOL, 0,
     N_("list only snapshots that are not leaves (with children)")},
3827 3828
    {"metadata", VSH_OT_BOOL, 0,
     N_("list only snapshots that have metadata that would prevent undefine")},
E
Eric Blake 已提交
3829 3830
    {"no-metadata", VSH_OT_BOOL, 0,
     N_("list only snapshots that have no metadata managed by libvirt")},
3831
    {"tree", VSH_OT_BOOL, 0, N_("list snapshots in a tree")},
3832
    {"from", VSH_OT_DATA, 0, N_("limit list to children of given snapshot")},
3833 3834
    {"current", VSH_OT_BOOL, 0,
     N_("limit list to children of current snapshot")},
3835
    {"descendants", VSH_OT_BOOL, 0, N_("with --from, list all descendants")},
3836 3837 3838
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
3839
static bool
3840 3841 3842
cmdSnapshotList(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
E
Eric Blake 已提交
3843
    bool ret = false;
3844
    unsigned int flags = 0;
3845
    bool show_parent = false;
3846 3847 3848 3849 3850 3851
    int i;
    xmlDocPtr xml = NULL;
    xmlXPathContextPtr ctxt = NULL;
    char *doc = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    char *state = NULL;
3852
    char *parent = NULL;
3853 3854
    long long creation_longlong;
    time_t creation_time_t;
3855 3856
    char timestr[100];
    struct tm time_info;
3857
    bool tree = vshCommandOptBool(cmd, "tree");
3858
    bool leaves = vshCommandOptBool(cmd, "leaves");
E
Eric Blake 已提交
3859
    bool no_leaves = vshCommandOptBool(cmd, "no-leaves");
3860 3861
    const char *from = NULL;
    virDomainSnapshotPtr start = NULL;
3862
    vshSnapshotListPtr snaplist = NULL;
3863

3864 3865 3866 3867 3868 3869 3870 3871 3872 3873
    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)
3874
        goto cleanup;
3875

3876
    if (vshCommandOptBool(cmd, "parent")) {
3877 3878
        if (vshCommandOptBool(cmd, "roots")) {
            vshError(ctl, "%s",
3879
                     _("--parent and --roots are mutually exclusive"));
3880
            goto cleanup;
3881
        }
3882 3883
        if (tree) {
            vshError(ctl, "%s",
3884
                     _("--parent and --tree are mutually exclusive"));
3885
            goto cleanup;
3886
        }
3887
        show_parent = true;
3888
    } else if (vshCommandOptBool(cmd, "roots")) {
3889 3890
        if (tree) {
            vshError(ctl, "%s",
3891
                     _("--roots and --tree are mutually exclusive"));
3892
            goto cleanup;
3893
        }
3894 3895 3896
        if (from) {
            vshError(ctl, "%s",
                     _("--roots and --from are mutually exclusive"));
3897
            goto cleanup;
3898
        }
3899 3900
        flags |= VIR_DOMAIN_SNAPSHOT_LIST_ROOTS;
    }
3901 3902 3903 3904
    if (leaves) {
        if (tree) {
            vshError(ctl, "%s",
                     _("--leaves and --tree are mutually exclusive"));
3905
            goto cleanup;
3906 3907 3908
        }
        flags |= VIR_DOMAIN_SNAPSHOT_LIST_LEAVES;
    }
E
Eric Blake 已提交
3909 3910 3911 3912 3913 3914 3915 3916
    if (no_leaves) {
        if (tree) {
            vshError(ctl, "%s",
                     _("--no-leaves and --tree are mutually exclusive"));
            goto cleanup;
        }
        flags |= VIR_DOMAIN_SNAPSHOT_LIST_NO_LEAVES;
    }
3917 3918 3919

    if (vshCommandOptBool(cmd, "metadata")) {
        flags |= VIR_DOMAIN_SNAPSHOT_LIST_METADATA;
3920
    }
E
Eric Blake 已提交
3921 3922 3923
    if (vshCommandOptBool(cmd, "no-metadata")) {
        flags |= VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA;
    }
3924

3925 3926 3927 3928 3929
    if (vshCommandOptBool(cmd, "descendants")) {
        if (!from) {
            vshError(ctl, "%s",
                     _("--descendants requires either --from or --current"));
            goto cleanup;
3930
        }
3931
        flags |= VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS;
3932 3933
    }

3934 3935
    if ((snaplist = vshSnapshotListCollect(ctl, dom, start, flags,
                                           tree)) == NULL)
3936 3937
        goto cleanup;

3938
    if (!tree) {
3939
        if (show_parent)
3940 3941 3942 3943 3944 3945
            vshPrintExtra(ctl, " %-20s %-25s %-15s %s",
                          _("Name"), _("Creation Time"), _("State"),
                          _("Parent"));
        else
            vshPrintExtra(ctl, " %-20s %-25s %s",
                          _("Name"), _("Creation Time"), _("State"));
E
Eric Blake 已提交
3946 3947
        vshPrintExtra(ctl, "\n"
"------------------------------------------------------------\n");
3948
    }
3949

3950
    if (!snaplist->nsnaps) {
3951 3952 3953
        ret = true;
        goto cleanup;
    }
3954

3955
    if (tree) {
3956 3957 3958 3959
        for (i = 0; i < snaplist->nsnaps; i++) {
            if (!snaplist->snaps[i].parent &&
                vshTreePrint(ctl, vshSnapshotListLookup, snaplist,
                             snaplist->nsnaps, i) < 0)
3960
                goto cleanup;
3961 3962 3963
        }
        ret = true;
        goto cleanup;
E
Eric Blake 已提交
3964 3965
    }

3966 3967
    for (i = 0; i < snaplist->nsnaps; i++) {
        const char *name;
3968

E
Eric Blake 已提交
3969 3970 3971 3972 3973 3974
        /* free up memory from previous iterations of the loop */
        VIR_FREE(parent);
        VIR_FREE(state);
        xmlXPathFreeContext(ctxt);
        xmlFreeDoc(xml);
        VIR_FREE(doc);
3975

3976 3977 3978
        snapshot = snaplist->snaps[i].snap;
        name = virDomainSnapshotGetName(snapshot);
        assert(name);
3979

E
Eric Blake 已提交
3980 3981 3982
        doc = virDomainSnapshotGetXMLDesc(snapshot, 0);
        if (!doc)
            continue;
3983

E
Eric Blake 已提交
3984 3985 3986
        xml = virXMLParseStringCtxt(doc, _("(domain_snapshot)"), &ctxt);
        if (!xml)
            continue;
3987

3988
        if (show_parent)
E
Eric Blake 已提交
3989 3990
            parent = virXPathString("string(/domainsnapshot/parent/name)",
                                    ctxt);
3991

E
Eric Blake 已提交
3992 3993 3994 3995 3996 3997 3998 3999 4000 4001
        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;
4002
        }
E
Eric Blake 已提交
4003 4004 4005 4006 4007 4008
        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",
4009
                     name, timestr, state, parent);
E
Eric Blake 已提交
4010
        else
4011
            vshPrint(ctl, " %-20s %-25s %s\n", name, timestr, state);
4012 4013
    }

E
Eric Blake 已提交
4014
    ret = true;
4015 4016 4017

cleanup:
    /* this frees up memory from the last iteration of the loop */
4018
    vshSnapshotListFree(snaplist);
4019
    VIR_FREE(parent);
4020
    VIR_FREE(state);
4021 4022
    if (start)
        virDomainSnapshotFree(start);
4023
    xmlXPathFreeContext(ctxt);
4024
    xmlFreeDoc(xml);
4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043
    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")},
4044 4045
    {"security-info", VSH_OT_BOOL, 0,
     N_("include security sensitive information in XML dump")},
4046 4047 4048
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
4049
static bool
4050 4051 4052
cmdSnapshotDumpXML(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
E
Eric Blake 已提交
4053
    bool ret = false;
4054
    const char *name = NULL;
4055 4056
    virDomainSnapshotPtr snapshot = NULL;
    char *xml = NULL;
4057 4058 4059 4060
    unsigned int flags = 0;

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

4062
    if (!vshConnectionUsability(ctl, ctl->conn))
4063 4064 4065 4066 4067 4068
        goto cleanup;

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

4069
    if (vshCommandOptString(cmd, "snapshotname", &name) <= 0)
4070 4071 4072 4073 4074 4075
        goto cleanup;

    snapshot = virDomainSnapshotLookupByName(dom, name, 0);
    if (snapshot == NULL)
        goto cleanup;

4076
    xml = virDomainSnapshotGetXMLDesc(snapshot, flags);
4077 4078 4079
    if (!xml)
        goto cleanup;

4080
    vshPrint(ctl, "%s", xml);
4081

E
Eric Blake 已提交
4082
    ret = true;
4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093

cleanup:
    VIR_FREE(xml);
    if (snapshot)
        virDomainSnapshotFree(snapshot);
    if (dom)
        virDomainFree(dom);

    return ret;
}

E
Eric Blake 已提交
4094 4095 4096 4097
/*
 * "snapshot-parent" command
 */
static const vshCmdInfo info_snapshot_parent[] = {
E
Eric Blake 已提交
4098
    {"help", N_("Get the name of the parent of a snapshot")},
E
Eric Blake 已提交
4099 4100 4101 4102 4103 4104
    {"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")},
4105 4106
    {"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 已提交
4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125
    {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;

4126 4127
    if (vshLookupSnapshot(ctl, cmd, "snapshotname", true, dom,
                          &snapshot, &name) < 0)
E
Eric Blake 已提交
4128 4129
        goto cleanup;

4130
    if (vshGetSnapshotParent(ctl, snapshot, &parent) < 0)
E
Eric Blake 已提交
4131
        goto cleanup;
4132 4133 4134 4135
    if (!parent) {
        vshError(ctl, _("snapshot '%s' has no parent"), name);
        goto cleanup;
    }
E
Eric Blake 已提交
4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150

    vshPrint(ctl, "%s", parent);

    ret = true;

cleanup:
    VIR_FREE(parent);
    if (snapshot)
        virDomainSnapshotFree(snapshot);
    if (dom)
        virDomainFree(dom);

    return ret;
}

4151
/*
4152
 * "snapshot-revert" command
4153
 */
4154
static const vshCmdInfo info_snapshot_revert[] = {
4155 4156 4157 4158 4159
    {"help", N_("Revert a domain to a snapshot")},
    {"desc", N_("Revert domain to snapshot")},
    {NULL, NULL}
};

4160
static const vshCmdOptDef opts_snapshot_revert[] = {
4161
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
4162 4163
    {"snapshotname", VSH_OT_DATA, 0, N_("snapshot name")},
    {"current", VSH_OT_BOOL, 0, N_("revert to current snapshot")},
4164 4165
    {"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 已提交
4166
    {"force", VSH_OT_BOOL, 0, N_("try harder on risky reverts")},
4167 4168 4169
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
4170
static bool
4171
cmdDomainSnapshotRevert(vshControl *ctl, const vshCmd *cmd)
4172 4173
{
    virDomainPtr dom = NULL;
E
Eric Blake 已提交
4174
    bool ret = false;
4175
    const char *name = NULL;
4176
    virDomainSnapshotPtr snapshot = NULL;
4177
    unsigned int flags = 0;
E
Eric Blake 已提交
4178 4179
    bool force = false;
    int result;
4180 4181 4182 4183 4184

    if (vshCommandOptBool(cmd, "running"))
        flags |= VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING;
    if (vshCommandOptBool(cmd, "paused"))
        flags |= VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED;
E
Eric Blake 已提交
4185 4186 4187 4188 4189 4190
    /* 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;
4191

4192
    if (!vshConnectionUsability(ctl, ctl->conn))
4193 4194 4195 4196 4197 4198
        goto cleanup;

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

4199 4200
    if (vshLookupSnapshot(ctl, cmd, "snapshotname", true, dom,
                          &snapshot, &name) < 0)
4201 4202
        goto cleanup;

E
Eric Blake 已提交
4203 4204 4205 4206 4207 4208 4209 4210 4211
    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)
4212 4213
        goto cleanup;

E
Eric Blake 已提交
4214
    ret = true;
4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235

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")},
4236 4237
    {"snapshotname", VSH_OT_DATA, 0, N_("snapshot name")},
    {"current", VSH_OT_BOOL, 0, N_("delete current snapshot")},
4238
    {"children", VSH_OT_BOOL, 0, N_("delete snapshot and all children")},
4239 4240 4241
    {"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")},
4242 4243 4244
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
4245
static bool
4246 4247 4248
cmdSnapshotDelete(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
E
Eric Blake 已提交
4249
    bool ret = false;
4250
    const char *name = NULL;
4251 4252 4253
    virDomainSnapshotPtr snapshot = NULL;
    unsigned int flags = 0;

4254
    if (!vshConnectionUsability(ctl, ctl->conn))
4255 4256 4257 4258 4259 4260
        goto cleanup;

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

4261 4262
    if (vshLookupSnapshot(ctl, cmd, "snapshotname", true, dom,
                          &snapshot, &name) < 0)
4263 4264 4265 4266
        goto cleanup;

    if (vshCommandOptBool(cmd, "children"))
        flags |= VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN;
4267 4268 4269 4270
    if (vshCommandOptBool(cmd, "children-only"))
        flags |= VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY;
    if (vshCommandOptBool(cmd, "metadata"))
        flags |= VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY;
4271

4272 4273 4274
    /* 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.  */
4275
    if (virDomainSnapshotDelete(snapshot, flags) == 0) {
4276 4277 4278 4279
        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);
4280 4281
    } else {
        vshError(ctl, _("Failed to delete snapshot %s"), name);
4282
        goto cleanup;
4283
    }
4284

E
Eric Blake 已提交
4285
    ret = true;
4286 4287 4288 4289 4290 4291 4292 4293 4294 4295

cleanup:
    if (snapshot)
        virDomainSnapshotFree(snapshot);
    if (dom)
        virDomainFree(dom);

    return ret;
}

4296 4297 4298 4299
/*
 * "qemu-monitor-command" command
 */
static const vshCmdInfo info_qemu_monitor_command[] = {
4300 4301
    {"help", N_("QEMU Monitor Command")},
    {"desc", N_("QEMU Monitor Command")},
4302 4303 4304 4305 4306
    {NULL, NULL}
};

static const vshCmdOptDef opts_qemu_monitor_command[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")},
4307
    {"hmp", VSH_OT_BOOL, 0, N_("command is in human monitor protocol")},
4308
    {"cmd", VSH_OT_ARGV, VSH_OFLAG_REQ, N_("command")},
4309 4310 4311
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
4312
static bool
4313 4314 4315
cmdQemuMonitorCommand(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
E
Eric Blake 已提交
4316
    bool ret = false;
4317
    char *monitor_cmd = NULL;
4318
    char *result = NULL;
4319
    unsigned int flags = 0;
4320 4321 4322
    const vshCmdOpt *opt = NULL;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    bool pad = false;
4323 4324 4325 4326 4327 4328 4329 4330

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

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

4331 4332 4333 4334 4335 4336 4337 4338
    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"));
4339 4340
        goto cleanup;
    }
4341
    monitor_cmd = virBufferContentAndReset(&buf);
4342

4343 4344 4345 4346
    if (vshCommandOptBool(cmd, "hmp"))
        flags |= VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP;

    if (virDomainQemuMonitorCommand(dom, monitor_cmd, &result, flags) < 0)
4347 4348 4349 4350
        goto cleanup;

    printf("%s\n", result);

E
Eric Blake 已提交
4351
    ret = true;
4352 4353 4354

cleanup:
    VIR_FREE(result);
4355
    VIR_FREE(monitor_cmd);
4356 4357 4358 4359 4360 4361
    if (dom)
        virDomainFree(dom);

    return ret;
}

4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381
/*
 * "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;
4382
    unsigned int pid_value; /* API uses unsigned int, not pid_t */
4383 4384 4385 4386

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

4387
    if (vshCommandOptUInt(cmd, "pid", &pid_value) <= 0) {
4388 4389 4390 4391
        vshError(ctl, "%s", _("missing pid value"));
        goto cleanup;
    }

4392
    if (!(dom = virDomainQemuAttach(ctl->conn, pid_value, flags)))
4393 4394 4395 4396
        goto cleanup;

    if (dom != NULL) {
        vshPrint(ctl, _("Domain %s attached to pid %u\n"),
4397
                 virDomainGetName(dom), pid_value);
4398 4399 4400
        virDomainFree(dom);
        ret = true;
    } else {
4401
        vshError(ctl, _("Failed to attach to pid %u"), pid_value);
4402 4403 4404 4405 4406 4407
    }

cleanup:
    return ret;
}

4408 4409 4410 4411 4412 4413 4414 4415
/* ---------------
 * Utils for work with command definition
 * ---------------
 */
static const char *
vshCmddefGetInfo(const vshCmdDef * cmd, const char *name)
{
    const vshCmdInfo *info;
4416

4417 4418 4419 4420 4421 4422
    for (info = cmd->info; info && info->name; info++) {
        if (STREQ(info->name, name))
            return info->data;
    }
    return NULL;
}
4423

4424 4425 4426 4427 4428 4429 4430
/* Validate that the options associated with cmd can be parsed.  */
static int
vshCmddefOptParse(const vshCmdDef *cmd, uint32_t *opts_need_arg,
                  uint32_t *opts_required)
{
    int i;
    bool optional = false;
4431

4432 4433
    *opts_need_arg = 0;
    *opts_required = 0;
4434

4435 4436
    if (!cmd->opts)
        return 0;
4437

4438 4439
    for (i = 0; cmd->opts[i].name; i++) {
        const vshCmdOptDef *opt = &cmd->opts[i];
4440 4441 4442 4443

        if (i > 31)
            return -1; /* too many options */
        if (opt->type == VSH_OT_BOOL) {
E
Eric Blake 已提交
4444
            if (opt->flags & VSH_OFLAG_REQ)
4445 4446 4447
                return -1; /* bool options can't be mandatory */
            continue;
        }
E
Eric Blake 已提交
4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459
        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 已提交
4460 4461
        if (opt->flags & VSH_OFLAG_REQ_OPT) {
            if (opt->flags & VSH_OFLAG_REQ)
L
Lai Jiangshan 已提交
4462 4463 4464 4465
                *opts_required |= 1 << i;
            continue;
        }

4466
        *opts_need_arg |= 1 << i;
E
Eric Blake 已提交
4467
        if (opt->flags & VSH_OFLAG_REQ) {
4468 4469 4470 4471 4472 4473
            if (optional)
                return -1; /* mandatory options must be listed first */
            *opts_required |= 1 << i;
        } else {
            optional = true;
        }
4474 4475 4476

        if (opt->type == VSH_OT_ARGV && cmd->opts[i + 1].name)
            return -1; /* argv option must be listed last */
4477 4478 4479 4480
    }
    return 0;
}

4481
static const vshCmdOptDef *
4482
vshCmddefGetOption(vshControl *ctl, const vshCmdDef *cmd, const char *name,
4483
                   uint32_t *opts_seen, int *opt_index)
4484
{
4485 4486 4487 4488
    int i;

    for (i = 0; cmd->opts && cmd->opts[i].name; i++) {
        const vshCmdOptDef *opt = &cmd->opts[i];
4489

4490
        if (STREQ(opt->name, name)) {
E
Eric Blake 已提交
4491 4492 4493 4494
            if (opt->type == VSH_OT_ALIAS) {
                name = opt->help;
                continue;
            }
4495
            if ((*opts_seen & (1 << i)) && opt->type != VSH_OT_ARGV) {
4496 4497 4498
                vshError(ctl, _("option --%s already seen"), name);
                return NULL;
            }
4499 4500
            *opts_seen |= 1 << i;
            *opt_index = i;
K
Karel Zak 已提交
4501
            return opt;
4502 4503 4504 4505 4506
        }
    }

    vshError(ctl, _("command '%s' doesn't support option --%s"),
             cmd->name, name);
K
Karel Zak 已提交
4507 4508 4509
    return NULL;
}

4510
static const vshCmdOptDef *
4511 4512
vshCmddefGetData(const vshCmdDef *cmd, uint32_t *opts_need_arg,
                 uint32_t *opts_seen)
4513
{
4514
    int i;
4515
    const vshCmdOptDef *opt;
K
Karel Zak 已提交
4516

4517 4518 4519 4520
    if (!*opts_need_arg)
        return NULL;

    /* Grab least-significant set bit */
E
Eric Blake 已提交
4521
    i = ffs(*opts_need_arg) - 1;
4522
    opt = &cmd->opts[i];
4523
    if (opt->type != VSH_OT_ARGV)
4524
        *opts_need_arg &= ~(1 << i);
4525
    *opts_seen |= 1 << i;
4526
    return opt;
K
Karel Zak 已提交
4527 4528
}

4529 4530 4531
/*
 * Checks for required options
 */
4532
static int
4533 4534
vshCommandCheckOpts(vshControl *ctl, const vshCmd *cmd, uint32_t opts_required,
                    uint32_t opts_seen)
4535
{
4536
    const vshCmdDef *def = cmd->def;
4537 4538 4539 4540 4541 4542 4543 4544 4545
    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];
4546

4547
            vshError(ctl,
4548
                     opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV ?
4549 4550 4551
                     _("command '%s' requires <%s> option") :
                     _("command '%s' requires --%s option"),
                     def->name, opt->name);
4552 4553
        }
    }
4554
    return -1;
4555 4556
}

4557
static const vshCmdDef *
4558 4559
vshCmddefSearch(const char *cmdname)
{
4560
    const vshCmdGrp *g;
4561
    const vshCmdDef *c;
4562

4563 4564
    for (g = cmdGroups; g->name; g++) {
        for (c = g->commands; c->name; c++) {
4565
            if (STREQ(c->name, cmdname))
4566 4567 4568 4569
                return c;
        }
    }

K
Karel Zak 已提交
4570 4571 4572
    return NULL;
}

4573 4574 4575 4576 4577 4578
static const vshCmdGrp *
vshCmdGrpSearch(const char *grpname)
{
    const vshCmdGrp *g;

    for (g = cmdGroups; g->name; g++) {
4579
        if (STREQ(g->name, grpname) || STREQ(g->keyword, grpname))
4580 4581 4582 4583 4584 4585
            return g;
    }

    return NULL;
}

E
Eric Blake 已提交
4586
static bool
4587 4588 4589 4590 4591 4592 4593
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 已提交
4594
        return false;
4595 4596 4597 4598 4599 4600 4601 4602 4603 4604
    } 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 已提交
4605
    return true;
4606 4607
}

E
Eric Blake 已提交
4608
static bool
4609
vshCmddefHelp(vshControl *ctl, const char *cmdname)
4610
{
4611
    const vshCmdDef *def = vshCmddefSearch(cmdname);
4612

K
Karel Zak 已提交
4613
    if (!def) {
4614
        vshError(ctl, _("command '%s' doesn't exist"), cmdname);
E
Eric Blake 已提交
4615
        return false;
4616
    } else {
E
Eric Blake 已提交
4617 4618
        /* Don't translate desc if it is "".  */
        const char *desc = vshCmddefGetInfo(def, "desc");
E
Eric Blake 已提交
4619
        const char *help = _(vshCmddefGetInfo(def, "help"));
4620
        char buf[256];
4621 4622
        uint32_t opts_need_arg;
        uint32_t opts_required;
4623
        bool shortopt = false; /* true if 'arg' works instead of '--opt arg' */
4624 4625 4626 4627

        if (vshCmddefOptParse(def, &opts_need_arg, &opts_required)) {
            vshError(ctl, _("internal error: bad options in command: '%s'"),
                     def->name);
E
Eric Blake 已提交
4628
            return false;
4629
        }
K
Karel Zak 已提交
4630

4631
        fputs(_("  NAME\n"), stdout);
4632 4633
        fprintf(stdout, "    %s - %s\n", def->name, help);

4634 4635 4636 4637 4638
        fputs(_("\n  SYNOPSIS\n"), stdout);
        fprintf(stdout, "    %s", def->name);
        if (def->opts) {
            const vshCmdOptDef *opt;
            for (opt = def->opts; opt->name; opt++) {
4639
                const char *fmt = "%s";
4640 4641
                switch (opt->type) {
                case VSH_OT_BOOL:
4642
                    fmt = "[--%s]";
4643 4644
                    break;
                case VSH_OT_INT:
E
Eric Blake 已提交
4645
                    /* xgettext:c-format */
E
Eric Blake 已提交
4646
                    fmt = ((opt->flags & VSH_OFLAG_REQ) ? "<%s>"
4647
                           : _("[--%s <number>]"));
4648 4649
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
4650 4651
                    break;
                case VSH_OT_STRING:
E
Eric Blake 已提交
4652 4653
                    /* xgettext:c-format */
                    fmt = _("[--%s <string>]");
4654 4655
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
4656 4657
                    break;
                case VSH_OT_DATA:
E
Eric Blake 已提交
4658
                    fmt = ((opt->flags & VSH_OFLAG_REQ) ? "<%s>" : "[<%s>]");
4659 4660
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
4661 4662 4663
                    break;
                case VSH_OT_ARGV:
                    /* xgettext:c-format */
4664 4665 4666 4667 4668 4669 4670 4671
                    if (shortopt) {
                        fmt = (opt->flags & VSH_OFLAG_REQ)
                            ? _("{[--%s] <string>}...")
                            : _("[[--%s] <string>]...");
                    } else {
                        fmt = (opt->flags & VSH_OFLAG_REQ) ? _("<%s>...")
                            : _("[<%s>]...");
                    }
4672
                    break;
E
Eric Blake 已提交
4673 4674 4675
                case VSH_OT_ALIAS:
                    /* aliases are intentionally undocumented */
                    continue;
4676
                default:
4677
                    assert(0);
4678
                }
4679
                fputc(' ', stdout);
E
Eric Blake 已提交
4680
                fprintf(stdout, fmt, opt->name);
4681
            }
K
Karel Zak 已提交
4682
        }
4683 4684 4685
        fputc('\n', stdout);

        if (desc[0]) {
4686
            /* Print the description only if it's not empty.  */
4687
            fputs(_("\n  DESCRIPTION\n"), stdout);
E
Eric Blake 已提交
4688
            fprintf(stdout, "    %s\n", _(desc));
K
Karel Zak 已提交
4689
        }
4690

K
Karel Zak 已提交
4691
        if (def->opts) {
4692
            const vshCmdOptDef *opt;
4693
            fputs(_("\n  OPTIONS\n"), stdout);
4694
            for (opt = def->opts; opt->name; opt++) {
4695 4696
                switch (opt->type) {
                case VSH_OT_BOOL:
K
Karel Zak 已提交
4697
                    snprintf(buf, sizeof(buf), "--%s", opt->name);
4698 4699
                    break;
                case VSH_OT_INT:
4700
                    snprintf(buf, sizeof(buf),
E
Eric Blake 已提交
4701
                             (opt->flags & VSH_OFLAG_REQ) ? _("[--%s] <number>")
4702
                             : _("--%s <number>"), opt->name);
4703 4704
                    break;
                case VSH_OT_STRING:
4705
                    /* OT_STRING should never be VSH_OFLAG_REQ */
4706
                    snprintf(buf, sizeof(buf), _("--%s <string>"), opt->name);
4707 4708
                    break;
                case VSH_OT_DATA:
4709 4710
                    snprintf(buf, sizeof(buf), _("[--%s] <string>"),
                             opt->name);
4711 4712
                    break;
                case VSH_OT_ARGV:
4713 4714 4715
                    snprintf(buf, sizeof(buf),
                             shortopt ? _("[--%s] <string>") : _("<%s>"),
                             opt->name);
4716
                    break;
E
Eric Blake 已提交
4717 4718
                case VSH_OT_ALIAS:
                    continue;
4719 4720 4721
                default:
                    assert(0);
                }
4722

E
Eric Blake 已提交
4723
                fprintf(stdout, "    %-15s  %s\n", buf, _(opt->help));
4724
            }
K
Karel Zak 已提交
4725 4726 4727
        }
        fputc('\n', stdout);
    }
E
Eric Blake 已提交
4728
    return true;
K
Karel Zak 已提交
4729 4730 4731 4732 4733 4734
}

/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
4735 4736 4737
static void
vshCommandOptFree(vshCmdOpt * arg)
{
K
Karel Zak 已提交
4738 4739
    vshCmdOpt *a = arg;

4740
    while (a) {
K
Karel Zak 已提交
4741
        vshCmdOpt *tmp = a;
4742

K
Karel Zak 已提交
4743 4744
        a = a->next;

4745 4746
        VIR_FREE(tmp->data);
        VIR_FREE(tmp);
K
Karel Zak 已提交
4747 4748 4749 4750
    }
}

static void
4751
vshCommandFree(vshCmd *cmd)
4752
{
K
Karel Zak 已提交
4753 4754
    vshCmd *c = cmd;

4755
    while (c) {
K
Karel Zak 已提交
4756
        vshCmd *tmp = c;
4757

K
Karel Zak 已提交
4758 4759 4760 4761
        c = c->next;

        if (tmp->opts)
            vshCommandOptFree(tmp->opts);
4762
        VIR_FREE(tmp);
K
Karel Zak 已提交
4763 4764 4765
    }
}

E
Eric Blake 已提交
4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776
/**
 * 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 已提交
4777
 */
E
Eric Blake 已提交
4778 4779
static int
vshCommandOpt(const vshCmd *cmd, const char *name, vshCmdOpt **opt)
4780
{
E
Eric Blake 已提交
4781 4782
    vshCmdOpt *candidate = cmd->opts;
    const vshCmdOptDef *valid = cmd->def->opts;
4783

E
Eric Blake 已提交
4784 4785 4786 4787 4788 4789 4790
    /* 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 已提交
4791
    }
E
Eric Blake 已提交
4792 4793 4794 4795 4796 4797 4798

    /* Option not present, see if command requires it.  */
    *opt = NULL;
    while (valid) {
        if (!valid->name)
            break;
        if (STREQ(name, valid->name))
E
Eric Blake 已提交
4799
            return (valid->flags & VSH_OFLAG_REQ) == 0 ? 0 : -1;
E
Eric Blake 已提交
4800 4801 4802 4803
        valid++;
    }
    /* If we got here, the name is unknown.  */
    return -2;
K
Karel Zak 已提交
4804 4805
}

E
Eric Blake 已提交
4806 4807
/**
 * vshCommandOptInt:
4808 4809 4810 4811 4812 4813 4814
 * @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 已提交
4815
 * 0 if option not found and not required (@value untouched)
4816
 * <0 in all other cases (@value untouched)
K
Karel Zak 已提交
4817 4818
 */
static int
4819
vshCommandOptInt(const vshCmd *cmd, const char *name, int *value)
4820
{
E
Eric Blake 已提交
4821 4822
    vshCmdOpt *arg;
    int ret;
4823

E
Eric Blake 已提交
4824 4825 4826 4827 4828 4829 4830
    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;
4831
    }
E
Eric Blake 已提交
4832

E
Eric Blake 已提交
4833 4834 4835
    if (virStrToLong_i(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
K
Karel Zak 已提交
4836 4837
}

4838

E
Eric Blake 已提交
4839 4840 4841 4842 4843 4844
/**
 * vshCommandOptUInt:
 * @cmd command reference
 * @name option name
 * @value result
 *
4845 4846 4847 4848 4849 4850
 * Convert option to unsigned int
 * See vshCommandOptInt()
 */
static int
vshCommandOptUInt(const vshCmd *cmd, const char *name, unsigned int *value)
{
E
Eric Blake 已提交
4851 4852
    vshCmdOpt *arg;
    int ret;
4853

E
Eric Blake 已提交
4854 4855 4856 4857 4858 4859 4860
    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;
4861
    }
E
Eric Blake 已提交
4862

E
Eric Blake 已提交
4863 4864 4865
    if (virStrToLong_ui(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
4866 4867 4868
}


4869
/*
E
Eric Blake 已提交
4870 4871 4872 4873 4874
 * vshCommandOptUL:
 * @cmd command reference
 * @name option name
 * @value result
 *
4875 4876 4877 4878 4879
 * Convert option to unsigned long
 * See vshCommandOptInt()
 */
static int
vshCommandOptUL(const vshCmd *cmd, const char *name, unsigned long *value)
4880
{
E
Eric Blake 已提交
4881 4882
    vshCmdOpt *arg;
    int ret;
4883

E
Eric Blake 已提交
4884 4885 4886 4887 4888 4889 4890
    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;
4891
    }
E
Eric Blake 已提交
4892

E
Eric Blake 已提交
4893 4894 4895
    if (virStrToLong_ul(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
4896 4897
}

E
Eric Blake 已提交
4898 4899 4900 4901 4902 4903
/**
 * vshCommandOptString:
 * @cmd command reference
 * @name option name
 * @value result
 *
K
Karel Zak 已提交
4904
 * Returns option as STRING
E
Eric Blake 已提交
4905 4906 4907 4908
 * 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 已提交
4909
 */
4910 4911
static int
vshCommandOptString(const vshCmd *cmd, const char *name, const char **value)
4912
{
E
Eric Blake 已提交
4913 4914 4915 4916 4917 4918 4919 4920 4921 4922
    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;
4923
    }
4924

E
Eric Blake 已提交
4925
    if (!*arg->data && !(arg->def->flags & VSH_OFLAG_EMPTY_OK)) {
E
Eric Blake 已提交
4926 4927 4928 4929
        return -1;
    }
    *value = arg->data;
    return 1;
K
Karel Zak 已提交
4930 4931
}

E
Eric Blake 已提交
4932 4933 4934 4935 4936 4937
/**
 * vshCommandOptLongLong:
 * @cmd command reference
 * @name option name
 * @value result
 *
4938
 * Returns option as long long
4939
 * See vshCommandOptInt()
4940
 */
4941 4942 4943
static int
vshCommandOptLongLong(const vshCmd *cmd, const char *name,
                      long long *value)
4944
{
E
Eric Blake 已提交
4945 4946
    vshCmdOpt *arg;
    int ret;
4947

E
Eric Blake 已提交
4948 4949 4950 4951 4952 4953 4954
    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;
4955
    }
E
Eric Blake 已提交
4956

E
Eric Blake 已提交
4957 4958 4959
    if (virStrToLong_ll(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
4960 4961
}

E
Eric Blake 已提交
4962 4963 4964 4965 4966 4967 4968 4969 4970
/**
 * vshCommandOptULongLong:
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Returns option as long long
 * See vshCommandOptInt()
 */
4971 4972 4973 4974
static int
vshCommandOptULongLong(const vshCmd *cmd, const char *name,
                       unsigned long long *value)
{
E
Eric Blake 已提交
4975 4976
    vshCmdOpt *arg;
    int ret;
4977

E
Eric Blake 已提交
4978 4979 4980 4981 4982 4983 4984
    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;
4985
    }
E
Eric Blake 已提交
4986

E
Eric Blake 已提交
4987 4988 4989
    if (virStrToLong_ull(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
4990 4991 4992
}


E
Eric Blake 已提交
4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022
/**
 * 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 已提交
5023 5024 5025 5026 5027 5028 5029 5030 5031
/**
 * 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 已提交
5032
 */
E
Eric Blake 已提交
5033
static bool
5034
vshCommandOptBool(const vshCmd *cmd, const char *name)
5035
{
E
Eric Blake 已提交
5036 5037 5038
    vshCmdOpt *dummy;

    return vshCommandOpt(cmd, name, &dummy) == 1;
K
Karel Zak 已提交
5039 5040
}

E
Eric Blake 已提交
5041 5042 5043 5044 5045
/**
 * vshCommandOptArgv:
 * @cmd command reference
 * @opt starting point for the search
 *
5046 5047
 * Returns the next argv argument after OPT (or the first one if OPT
 * is NULL), or NULL if no more are present.
5048
 *
5049
 * Requires that a VSH_OT_ARGV option be last in the
5050 5051
 * list of supported options in CMD->def->opts.
 */
5052 5053
static const vshCmdOpt *
vshCommandOptArgv(const vshCmd *cmd, const vshCmdOpt *opt)
5054
{
5055
    opt = opt ? opt->next : cmd->opts;
5056 5057

    while (opt) {
E
Eric Blake 已提交
5058
        if (opt->def->type == VSH_OT_ARGV) {
5059
            return opt;
5060 5061 5062 5063 5064 5065
        }
        opt = opt->next;
    }
    return NULL;
}

J
Jim Meyering 已提交
5066 5067 5068 5069
/* Determine whether CMD->opts includes an option with name OPTNAME.
   If not, give a diagnostic and return false.
   If so, return true.  */
static bool
5070
cmd_has_option(vshControl *ctl, const vshCmd *cmd, const char *optname)
J
Jim Meyering 已提交
5071 5072 5073 5074 5075 5076
{
    /* 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) {
5077
        if (STREQ(opt->def->name, optname) && opt->def->type == VSH_OT_DATA) {
J
Jim Meyering 已提交
5078 5079 5080 5081 5082 5083
            found = true;
            break;
        }
    }

    if (!found)
5084
        vshError(ctl, _("internal error: virsh %s: no %s VSH_OT_DATA option"),
J
Jim Meyering 已提交
5085 5086 5087
                 cmd->def->name, optname);
    return found;
}
5088

K
Karel Zak 已提交
5089
static virDomainPtr
J
Jim Meyering 已提交
5090
vshCommandOptDomainBy(vshControl *ctl, const vshCmd *cmd,
5091
                      const char **name, int flag)
5092
{
K
Karel Zak 已提交
5093
    virDomainPtr dom = NULL;
5094
    const char *n = NULL;
K
Karel Zak 已提交
5095
    int id;
J
Jim Meyering 已提交
5096
    const char *optname = "domain";
5097
    if (!cmd_has_option(ctl, cmd, optname))
J
Jim Meyering 已提交
5098
        return NULL;
5099

5100
    if (vshCommandOptString(cmd, optname, &n) <= 0)
5101 5102
        return NULL;

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

K
Karel Zak 已提交
5106 5107
    if (name)
        *name = n;
5108

K
Karel Zak 已提交
5109
    /* try it by ID */
5110
    if (flag & VSH_BYID) {
5111
        if (virStrToLong_i(n, NULL, 10, &id) == 0 && id >= 0) {
5112 5113
            vshDebug(ctl, VSH_ERR_DEBUG,
                     "%s: <%s> seems like domain ID\n",
K
Karel Zak 已提交
5114 5115 5116
                     cmd->def->name, optname);
            dom = virDomainLookupByID(ctl->conn, id);
        }
5117
    }
K
Karel Zak 已提交
5118
    /* try it by UUID */
5119
    if (dom==NULL && (flag & VSH_BYUUID) && strlen(n)==VIR_UUID_STRING_BUFLEN-1) {
5120
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as domain UUID\n",
5121
                 cmd->def->name, optname);
K
Karel Zak 已提交
5122
        dom = virDomainLookupByUUIDString(ctl->conn, n);
K
Karel Zak 已提交
5123
    }
K
Karel Zak 已提交
5124
    /* try it by NAME */
5125
    if (dom==NULL && (flag & VSH_BYNAME)) {
5126
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as domain NAME\n",
5127
                 cmd->def->name, optname);
K
Karel Zak 已提交
5128
        dom = virDomainLookupByName(ctl->conn, n);
5129
    }
K
Karel Zak 已提交
5130

5131
    if (!dom)
5132
        vshError(ctl, _("failed to get domain '%s'"), n);
5133

K
Karel Zak 已提交
5134 5135 5136
    return dom;
}

5137 5138
static virNWFilterPtr
vshCommandOptNWFilterBy(vshControl *ctl, const vshCmd *cmd,
5139
                        const char **name, int flag)
5140 5141
{
    virNWFilterPtr nwfilter = NULL;
5142
    const char *n = NULL;
5143
    const char *optname = "nwfilter";
5144
    if (!cmd_has_option(ctl, cmd, optname))
5145 5146
        return NULL;

5147
    if (vshCommandOptString(cmd, optname, &n) <= 0)
5148 5149
        return NULL;

5150
    vshDebug(ctl, VSH_ERR_INFO, "%s: found option <%s>: %s\n",
5151 5152 5153 5154 5155 5156
             cmd->def->name, optname, n);

    if (name)
        *name = n;

    /* try it by UUID */
E
Eric Blake 已提交
5157
    if ((flag & VSH_BYUUID) && strlen(n) == VIR_UUID_STRING_BUFLEN-1) {
5158
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as nwfilter UUID\n",
5159 5160 5161 5162 5163
                 cmd->def->name, optname);
        nwfilter = virNWFilterLookupByUUIDString(ctl->conn, n);
    }
    /* try it by NAME */
    if (nwfilter == NULL && (flag & VSH_BYNAME)) {
5164
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as nwfilter NAME\n",
5165 5166 5167 5168 5169 5170 5171 5172 5173 5174
                 cmd->def->name, optname);
        nwfilter = virNWFilterLookupByName(ctl->conn, n);
    }

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

    return nwfilter;
}

5175
static virSecretPtr
5176
vshCommandOptSecret(vshControl *ctl, const vshCmd *cmd, const char **name)
5177 5178
{
    virSecretPtr secret = NULL;
5179
    const char *n = NULL;
5180 5181
    const char *optname = "secret";

5182
    if (!cmd_has_option(ctl, cmd, optname))
5183 5184
        return NULL;

5185
    if (vshCommandOptString(cmd, optname, &n) <= 0)
5186 5187
        return NULL;

5188 5189
    vshDebug(ctl, VSH_ERR_DEBUG,
             "%s: found option <%s>: %s\n", cmd->def->name, optname, n);
5190 5191 5192 5193 5194 5195 5196

    if (name != NULL)
        *name = n;

    secret = virSecretLookupByUUIDString(ctl->conn, n);

    if (secret == NULL)
5197
        vshError(ctl, _("failed to get secret '%s'"), n);
5198 5199 5200 5201

    return secret;
}

K
Karel Zak 已提交
5202 5203 5204
/*
 * Executes command(s) and returns return code from last command
 */
E
Eric Blake 已提交
5205
static bool
5206
vshCommandRun(vshControl *ctl, const vshCmd *cmd)
5207
{
E
Eric Blake 已提交
5208
    bool ret = true;
5209 5210

    while (cmd) {
K
Karel Zak 已提交
5211
        struct timeval before, after;
5212
        bool enable_timing = ctl->timing;
5213

5214 5215
        if ((ctl->conn == NULL || disconnected) &&
            !(cmd->def->flags & VSH_CMD_FLAG_NOCONNECT))
5216 5217
            vshReconnect(ctl);

5218
        if (enable_timing)
K
Karel Zak 已提交
5219
            GETTIMEOFDAY(&before);
5220

K
Karel Zak 已提交
5221 5222
        ret = cmd->def->handler(ctl, cmd);

5223
        if (enable_timing)
K
Karel Zak 已提交
5224
            GETTIMEOFDAY(&after);
5225

5226 5227 5228 5229 5230 5231 5232 5233 5234 5235
        /* 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++;

5236
        if (!ret)
J
John Levon 已提交
5237 5238
            virshReportError(ctl);

5239
        if (!ret && disconnected != 0)
5240 5241
            vshReconnect(ctl);

5242
        if (STREQ(cmd->def->name, "quit"))        /* hack ... */
K
Karel Zak 已提交
5243 5244
            return ret;

5245
        if (enable_timing)
5246
            vshPrint(ctl, _("\n(Time: %.3f ms)\n\n"),
5247 5248
                     DIFF_MSEC(&after, &before));
        else
K
Karel Zak 已提交
5249
            vshPrintExtra(ctl, "\n");
K
Karel Zak 已提交
5250 5251 5252 5253 5254 5255
        cmd = cmd->next;
    }
    return ret;
}

/* ---------------
5256
 * Command parsing
K
Karel Zak 已提交
5257 5258 5259
 * ---------------
 */

5260 5261 5262 5263 5264 5265 5266 5267
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 {
5268
    vshCommandToken(*getNextArg)(vshControl *, struct __vshCommandParser *,
5269
                                  char **);
L
Lai Jiangshan 已提交
5270
    /* vshCommandStringGetArg() */
5271
    char *pos;
L
Lai Jiangshan 已提交
5272 5273 5274
    /* vshCommandArgvGetArg() */
    char **arg_pos;
    char **arg_end;
5275 5276
} vshCommandParser;

E
Eric Blake 已提交
5277
static bool
5278
vshCommandParse(vshControl *ctl, vshCommandParser *parser)
5279
{
K
Karel Zak 已提交
5280 5281 5282
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
5283

K
Karel Zak 已提交
5284 5285 5286 5287
    if (ctl->cmd) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
5288

5289
    while (1) {
K
Karel Zak 已提交
5290
        vshCmdOpt *last = NULL;
5291
        const vshCmdDef *cmd = NULL;
5292
        vshCommandToken tk;
L
Lai Jiangshan 已提交
5293
        bool data_only = false;
5294 5295 5296
        uint32_t opts_need_arg = 0;
        uint32_t opts_required = 0;
        uint32_t opts_seen = 0;
5297

K
Karel Zak 已提交
5298
        first = NULL;
5299

5300
        while (1) {
5301
            const vshCmdOptDef *opt = NULL;
5302

K
Karel Zak 已提交
5303
            tkdata = NULL;
5304
            tk = parser->getNextArg(ctl, parser, &tkdata);
5305 5306

            if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
5307
                goto syntaxError;
H
Hu Tao 已提交
5308 5309
            if (tk != VSH_TK_ARG) {
                VIR_FREE(tkdata);
5310
                break;
H
Hu Tao 已提交
5311
            }
5312 5313

            if (cmd == NULL) {
K
Karel Zak 已提交
5314 5315
                /* first token must be command name */
                if (!(cmd = vshCmddefSearch(tkdata))) {
5316
                    vshError(ctl, _("unknown command: '%s'"), tkdata);
5317
                    goto syntaxError;   /* ... or ignore this command only? */
K
Karel Zak 已提交
5318
                }
5319 5320 5321 5322 5323 5324 5325
                if (vshCmddefOptParse(cmd, &opts_need_arg,
                                      &opts_required) < 0) {
                    vshError(ctl,
                             _("internal error: bad options in command: '%s'"),
                             tkdata);
                    goto syntaxError;
                }
5326
                VIR_FREE(tkdata);
L
Lai Jiangshan 已提交
5327 5328 5329 5330
            } else if (data_only) {
                goto get_data;
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       c_isalnum(tkdata[2])) {
5331
                char *optstr = strchr(tkdata + 2, '=');
5332 5333
                int opt_index;

5334 5335 5336 5337
                if (optstr) {
                    *optstr = '\0'; /* convert the '=' to '\0' */
                    optstr = vshStrdup(ctl, optstr + 1);
                }
5338
                if (!(opt = vshCmddefGetOption(ctl, cmd, tkdata + 2,
5339
                                               &opts_seen, &opt_index))) {
5340
                    VIR_FREE(optstr);
K
Karel Zak 已提交
5341 5342
                    goto syntaxError;
                }
5343
                VIR_FREE(tkdata);
K
Karel Zak 已提交
5344 5345 5346

                if (opt->type != VSH_OT_BOOL) {
                    /* option data */
5347 5348 5349
                    if (optstr)
                        tkdata = optstr;
                    else
5350
                        tk = parser->getNextArg(ctl, parser, &tkdata);
5351
                    if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
5352
                        goto syntaxError;
5353
                    if (tk != VSH_TK_ARG) {
5354
                        vshError(ctl,
5355
                                 _("expected syntax: --%s <%s>"),
5356 5357
                                 opt->name,
                                 opt->type ==
5358
                                 VSH_OT_INT ? _("number") : _("string"));
K
Karel Zak 已提交
5359 5360
                        goto syntaxError;
                    }
5361 5362
                    if (opt->type != VSH_OT_ARGV)
                        opts_need_arg &= ~(1 << opt_index);
5363 5364 5365 5366 5367 5368 5369 5370
                } else {
                    tkdata = NULL;
                    if (optstr) {
                        vshError(ctl, _("invalid '=' after option --%s"),
                                opt->name);
                        VIR_FREE(optstr);
                        goto syntaxError;
                    }
K
Karel Zak 已提交
5371
                }
L
Lai Jiangshan 已提交
5372 5373 5374 5375
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       tkdata[2] == '\0') {
                data_only = true;
                continue;
5376
            } else {
L
Lai Jiangshan 已提交
5377
get_data:
5378 5379
                if (!(opt = vshCmddefGetData(cmd, &opts_need_arg,
                                             &opts_seen))) {
5380
                    vshError(ctl, _("unexpected data '%s'"), tkdata);
K
Karel Zak 已提交
5381 5382 5383 5384 5385
                    goto syntaxError;
                }
            }
            if (opt) {
                /* save option */
5386
                vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));
5387

K
Karel Zak 已提交
5388 5389 5390 5391
                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;
5392

K
Karel Zak 已提交
5393 5394 5395 5396 5397
                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;
5398

5399
                vshDebug(ctl, VSH_ERR_INFO, "%s: %s(%s): %s\n",
5400 5401
                         cmd->name,
                         opt->name,
5402 5403
                         opt->type != VSH_OT_BOOL ? _("optdata") : _("bool"),
                         opt->type != VSH_OT_BOOL ? arg->data : _("(none)"));
K
Karel Zak 已提交
5404 5405
            }
        }
5406

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

K
Karel Zak 已提交
5411 5412 5413 5414
            c->opts = first;
            c->def = cmd;
            c->next = NULL;

5415
            if (vshCommandCheckOpts(ctl, c, opts_required, opts_seen) < 0) {
5416
                VIR_FREE(c);
5417
                goto syntaxError;
5418
            }
5419

K
Karel Zak 已提交
5420 5421 5422 5423 5424 5425
            if (!ctl->cmd)
                ctl->cmd = c;
            if (clast)
                clast->next = c;
            clast = c;
        }
5426 5427 5428

        if (tk == VSH_TK_END)
            break;
K
Karel Zak 已提交
5429
    }
5430

E
Eric Blake 已提交
5431
    return true;
K
Karel Zak 已提交
5432

5433
 syntaxError:
5434
    if (ctl->cmd) {
K
Karel Zak 已提交
5435
        vshCommandFree(ctl->cmd);
5436 5437
        ctl->cmd = NULL;
    }
K
Karel Zak 已提交
5438 5439
    if (first)
        vshCommandOptFree(first);
5440
    VIR_FREE(tkdata);
E
Eric Blake 已提交
5441
    return false;
K
Karel Zak 已提交
5442 5443
}

5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461
/* --------------------
 * 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 已提交
5462 5463
static bool
vshCommandArgvParse(vshControl *ctl, int nargs, char **argv)
5464 5465 5466 5467
{
    vshCommandParser parser;

    if (nargs <= 0)
E
Eric Blake 已提交
5468
        return false;
5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540

    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 已提交
5541 5542
static bool
vshCommandStringParse(vshControl *ctl, char *cmdstr)
5543 5544 5545 5546
{
    vshCommandParser parser;

    if (cmdstr == NULL || *cmdstr == '\0')
E
Eric Blake 已提交
5547
        return false;
5548 5549 5550 5551 5552 5553

    parser.pos = cmdstr;
    parser.getNextArg = vshCommandStringGetArg;
    return vshCommandParse(ctl, &parser);
}

K
Karel Zak 已提交
5554
/* ---------------
5555
 * Misc utils
K
Karel Zak 已提交
5556 5557
 * ---------------
 */
5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585
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;
}

5586 5587
/* Return a non-NULL string representation of a typed parameter; exit
 * if we are out of memory.  */
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 5614 5615 5616 5617 5618
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;

5619 5620 5621 5622
    case VIR_TYPED_PARAM_STRING:
        str = vshStrdup(ctl, item->value.s);
        break;

5623
    default:
5624
        vshError(ctl, _("unimplemented parameter type %d"), item->type);
5625 5626
    }

5627
    if (ret < 0) {
5628
        vshError(ctl, "%s", _("Out of memory"));
5629 5630
        exit(EXIT_FAILURE);
    }
5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653
    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;
}

E
Eric Blake 已提交
5654
static bool
5655
vshConnectionUsability(vshControl *ctl, virConnectPtr conn)
5656
{
5657 5658
    /* TODO: use something like virConnectionState() to
     *       check usability of the connection
K
Karel Zak 已提交
5659 5660
     */
    if (!conn) {
5661
        vshError(ctl, "%s", _("no valid connection"));
E
Eric Blake 已提交
5662
        return false;
K
Karel Zak 已提交
5663
    }
E
Eric Blake 已提交
5664
    return true;
K
Karel Zak 已提交
5665 5666
}

K
Karel Zak 已提交
5667
static void
5668
vshDebug(vshControl *ctl, int level, const char *format, ...)
5669
{
K
Karel Zak 已提交
5670
    va_list ap;
5671
    char *str;
K
Karel Zak 已提交
5672

5673 5674 5675 5676 5677 5678 5679
    /* Aligning log levels to that of libvirt.
     * Traces with levels >=  user-specified-level
     * gets logged into file
     */
    if (level < ctl->debug)
        return;

5680
    va_start(ap, format);
5681
    vshOutputLogFile(ctl, level, format, ap);
5682 5683
    va_end(ap);

K
Karel Zak 已提交
5684
    va_start(ap, format);
5685 5686 5687 5688 5689
    if (virVasprintf(&str, format, ap) < 0) {
        /* Skip debug messages on low memory */
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
5690
    va_end(ap);
5691 5692
    fputs(str, stdout);
    VIR_FREE(str);
K
Karel Zak 已提交
5693 5694 5695
}

static void
5696
vshPrintExtra(vshControl *ctl, const char *format, ...)
5697
{
K
Karel Zak 已提交
5698
    va_list ap;
5699
    char *str;
5700

5701
    if (ctl && ctl->quiet)
K
Karel Zak 已提交
5702
        return;
5703

K
Karel Zak 已提交
5704
    va_start(ap, format);
5705 5706 5707 5708 5709
    if (virVasprintf(&str, format, ap) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
5710
    va_end(ap);
5711
    fputs(str, stdout);
5712
    VIR_FREE(str);
K
Karel Zak 已提交
5713 5714
}

K
Karel Zak 已提交
5715

K
Karel Zak 已提交
5716
static void
5717
vshError(vshControl *ctl, const char *format, ...)
5718
{
K
Karel Zak 已提交
5719
    va_list ap;
5720
    char *str;
5721

5722 5723 5724 5725 5726
    if (ctl != NULL) {
        va_start(ap, format);
        vshOutputLogFile(ctl, VSH_ERR_ERROR, format, ap);
        va_end(ap);
    }
5727

5728 5729 5730 5731
    /* 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);
5732
    fputs(_("error: "), stderr);
5733

K
Karel Zak 已提交
5734
    va_start(ap, format);
5735 5736 5737
    /* We can't recursively call vshError on an OOM situation, so ignore
       failure here. */
    ignore_value(virVasprintf(&str, format, ap));
K
Karel Zak 已提交
5738 5739
    va_end(ap);

5740
    fprintf(stderr, "%s\n", NULLSTR(str));
5741
    fflush(stderr);
5742
    VIR_FREE(str);
K
Karel Zak 已提交
5743 5744
}

5745

J
Jiri Denemark 已提交
5746 5747 5748 5749 5750
static void
vshEventLoop(void *opaque)
{
    vshControl *ctl = opaque;

5751 5752 5753 5754 5755 5756 5757 5758 5759 5760
    while (1) {
        bool quit;
        virMutexLock(&ctl->lock);
        quit = ctl->quit;
        virMutexUnlock(&ctl->lock);

        if (quit)
            break;

        if (virEventRunDefaultImpl() < 0)
J
Jiri Denemark 已提交
5761 5762 5763 5764 5765
            virshReportError(ctl);
    }
}


K
Karel Zak 已提交
5766
/*
5767
 * Initialize connection.
K
Karel Zak 已提交
5768
 */
E
Eric Blake 已提交
5769
static bool
5770
vshInit(vshControl *ctl)
5771
{
5772 5773
    char *debugEnv;

K
Karel Zak 已提交
5774
    if (ctl->conn)
E
Eric Blake 已提交
5775
        return false;
K
Karel Zak 已提交
5776

J
Jiri Denemark 已提交
5777
    if (ctl->debug == VSH_DEBUG_DEFAULT) {
5778 5779 5780
        /* log level not set from commandline, check env variable */
        debugEnv = getenv("VIRSH_DEBUG");
        if (debugEnv) {
J
Jiri Denemark 已提交
5781 5782 5783
            int debug;
            if (virStrToLong_i(debugEnv, NULL, 10, &debug) < 0 ||
                debug < VSH_ERR_DEBUG || debug > VSH_ERR_ERROR) {
5784 5785
                vshError(ctl, "%s",
                         _("VIRSH_DEBUG not set with a valid numeric value"));
J
Jiri Denemark 已提交
5786 5787
            } else {
                ctl->debug = debug;
5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799
            }
        }
    }

    if (ctl->logfile == NULL) {
        /* log file not set from cmdline */
        debugEnv = getenv("VIRSH_LOG_FILE");
        if (debugEnv && *debugEnv) {
            ctl->logfile = vshStrdup(ctl, debugEnv);
        }
    }

5800 5801
    vshOpenLogFile(ctl);

5802 5803
    /* set up the library error handler */
    virSetErrorFunc(NULL, virshErrorHandler);
5804

5805 5806 5807
    /* set up the signals handlers to catch disconnections */
    vshSetupSignals();

5808
    if (virEventRegisterDefaultImpl() < 0)
E
Eric Blake 已提交
5809
        return false;
5810

J
Jiri Denemark 已提交
5811 5812 5813 5814
    if (virThreadCreate(&ctl->eventLoop, true, vshEventLoop, ctl) < 0)
        return false;
    ctl->eventLoopStarted = true;

5815 5816 5817 5818
    if (ctl->name) {
        ctl->conn = virConnectOpenAuth(ctl->name,
                                       virConnectAuthPtrDefault,
                                       ctl->readonly ? VIR_CONNECT_RO : 0);
5819

5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830
        /* 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;
        }
5831
    }
K
Karel Zak 已提交
5832

E
Eric Blake 已提交
5833
    return true;
K
Karel Zak 已提交
5834 5835
}

5836 5837
#define LOGFILE_FLAGS (O_WRONLY | O_APPEND | O_CREAT | O_SYNC)

5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856
/**
 * 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:
5857
                vshError(ctl, "%s",
J
Jim Meyering 已提交
5858
                         _("failed to get the log file information"));
5859
                exit(EXIT_FAILURE);
5860 5861 5862
        }
    } else {
        if (!S_ISREG(st.st_mode)) {
5863 5864
            vshError(ctl, "%s", _("the log path is not a file"));
            exit(EXIT_FAILURE);
5865 5866 5867 5868
        }
    }

    /* log file open */
5869
    if ((ctl->log_fd = open(ctl->logfile, LOGFILE_FLAGS, FILE_MODE)) < 0) {
5870
        vshError(ctl, "%s",
J
Jim Meyering 已提交
5871
                 _("failed to open the log file. check the log file path"));
5872
        exit(EXIT_FAILURE);
5873 5874 5875 5876 5877 5878 5879 5880 5881
    }
}

/**
 * vshOutputLogFile:
 *
 * Outputting an error to log file.
 */
static void
5882 5883
vshOutputLogFile(vshControl *ctl, int log_level, const char *msg_format,
                 va_list ap)
5884
{
5885 5886 5887
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char *str;
    size_t len;
5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901
    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);
5902
    virBufferAsprintf(&buf, "[%d.%02d.%02d %02d:%02d:%02d %s %d] ",
5903 5904 5905 5906 5907 5908
                      (1900 + stTm->tm_year),
                      (1 + stTm->tm_mon),
                      stTm->tm_mday,
                      stTm->tm_hour,
                      stTm->tm_min,
                      stTm->tm_sec,
5909 5910
                      SIGN_NAME,
                      (int) getpid());
5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930
    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;
    }
5931 5932 5933
    virBufferAsprintf(&buf, "%s ", lvl);
    virBufferVasprintf(&buf, msg_format, ap);
    virBufferAddChar(&buf, '\n');
5934

5935 5936
    if (virBufferError(&buf))
        goto error;
5937

5938 5939 5940 5941 5942
    str = virBufferContentAndReset(&buf);
    len = strlen(str);
    if (len > 1 && str[len - 2] == '\n') {
        str[len - 1] = '\0';
        len--;
5943
    }
5944

5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955
    /* 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);
5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966
}

/**
 * vshCloseLogFile:
 *
 * Close log file.
 */
static void
vshCloseLogFile(vshControl *ctl)
{
    /* log file close */
5967 5968 5969
    if (VIR_CLOSE(ctl->log_fd) < 0) {
        vshError(ctl, _("%s: failed to write log file: %s"),
                 ctl->logfile ? ctl->logfile : "?", strerror (errno));
5970 5971 5972
    }

    if (ctl->logfile) {
5973
        VIR_FREE(ctl->logfile);
5974 5975 5976 5977
        ctl->logfile = NULL;
    }
}

5978
#ifdef USE_READLINE
5979

K
Karel Zak 已提交
5980 5981 5982 5983 5984
/* -----------------
 * Readline stuff
 * -----------------
 */

5985
/*
K
Karel Zak 已提交
5986 5987
 * Generator function for command completion.  STATE lets us
 * know whether to start from scratch; without any state
5988
 * (i.e. STATE == 0), then we start at the top of the list.
K
Karel Zak 已提交
5989 5990
 */
static char *
5991 5992
vshReadlineCommandGenerator(const char *text, int state)
{
5993
    static int grp_list_index, cmd_list_index, len;
K
Karel Zak 已提交
5994
    const char *name;
5995 5996
    const vshCmdGrp *grp;
    const vshCmdDef *cmds;
K
Karel Zak 已提交
5997 5998

    if (!state) {
5999 6000
        grp_list_index = 0;
        cmd_list_index = 0;
6001
        len = strlen(text);
K
Karel Zak 已提交
6002 6003
    }

6004 6005
    grp = cmdGroups;

K
Karel Zak 已提交
6006
    /* Return the next name which partially matches from the
6007
     * command list.
K
Karel Zak 已提交
6008
     */
6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022
    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 已提交
6023 6024 6025 6026 6027 6028 6029
    }

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

static char *
6030 6031
vshReadlineOptionsGenerator(const char *text, int state)
{
K
Karel Zak 已提交
6032
    static int list_index, len;
6033
    static const vshCmdDef *cmd = NULL;
K
Karel Zak 已提交
6034
    const char *name;
K
Karel Zak 已提交
6035 6036 6037 6038 6039 6040 6041 6042 6043

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

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

6044
        cmdname = vshCalloc(NULL, (p - rl_line_buffer) + 1, 1);
6045
        memcpy(cmdname, rl_line_buffer, p - rl_line_buffer);
K
Karel Zak 已提交
6046 6047 6048

        cmd = vshCmddefSearch(cmdname);
        list_index = 0;
6049
        len = strlen(text);
6050
        VIR_FREE(cmdname);
K
Karel Zak 已提交
6051 6052 6053 6054
    }

    if (!cmd)
        return NULL;
6055

6056 6057 6058
    if (!cmd->opts)
        return NULL;

K
Karel Zak 已提交
6059
    while ((name = cmd->opts[list_index].name)) {
6060
        const vshCmdOptDef *opt = &cmd->opts[list_index];
K
Karel Zak 已提交
6061
        char *res;
6062

K
Karel Zak 已提交
6063
        list_index++;
6064

6065
        if (opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV)
K
Karel Zak 已提交
6066 6067
            /* ignore non --option */
            continue;
6068

K
Karel Zak 已提交
6069
        if (len > 2) {
6070
            if (STRNEQLEN(name, text + 2, len - 2))
K
Karel Zak 已提交
6071 6072
                continue;
        }
6073
        res = vshMalloc(NULL, strlen(name) + 3);
6074
        snprintf(res, strlen(name) + 3,  "--%s", name);
K
Karel Zak 已提交
6075 6076 6077 6078 6079 6080 6081 6082
        return res;
    }

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

static char **
6083 6084 6085
vshReadlineCompletion(const char *text, int start,
                      int end ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
6086 6087
    char **matches = (char **) NULL;

6088
    if (start == 0)
K
Karel Zak 已提交
6089
        /* command name generator */
6090
        matches = rl_completion_matches(text, vshReadlineCommandGenerator);
K
Karel Zak 已提交
6091 6092
    else
        /* commands options */
6093
        matches = rl_completion_matches(text, vshReadlineOptionsGenerator);
K
Karel Zak 已提交
6094 6095 6096 6097
    return matches;
}


6098 6099
static int
vshReadlineInit(vshControl *ctl)
6100
{
6101 6102
    char *userdir = NULL;

K
Karel Zak 已提交
6103 6104 6105 6106 6107
    /* 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;
6108 6109 6110

    /* Limit the total size of the history buffer */
    stifle_history(500);
6111

6112
    /* Prepare to read/write history from/to the $XDG_CACHE_HOME/virsh/history file */
6113
    userdir = virGetUserCacheDirectory();
6114

6115 6116
    if (userdir == NULL) {
        vshError(ctl, "%s", _("Could not determine home directory"));
6117
        return -1;
6118
    }
6119

6120
    if (virAsprintf(&ctl->historydir, "%s/virsh", userdir) < 0) {
6121
        vshError(ctl, "%s", _("Out of memory"));
6122
        VIR_FREE(userdir);
6123 6124 6125 6126 6127
        return -1;
    }

    if (virAsprintf(&ctl->historyfile, "%s/history", ctl->historydir) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
6128
        VIR_FREE(userdir);
6129 6130 6131
        return -1;
    }

6132
    VIR_FREE(userdir);
6133 6134 6135 6136 6137 6138 6139

    read_history(ctl->historyfile);

    return 0;
}

static void
6140
vshReadlineDeinit(vshControl *ctl)
6141 6142
{
    if (ctl->historyfile != NULL) {
6143 6144
        if (virFileMakePathWithMode(ctl->historydir, 0755) < 0 &&
            errno != EEXIST) {
6145 6146
            char ebuf[1024];
            vshError(ctl, _("Failed to create '%s': %s"),
6147
                     ctl->historydir, virStrerror(errno, ebuf, sizeof(ebuf)));
E
Eric Blake 已提交
6148
        } else {
6149
            write_history(ctl->historyfile);
E
Eric Blake 已提交
6150
        }
6151 6152
    }

6153 6154
    VIR_FREE(ctl->historydir);
    VIR_FREE(ctl->historyfile);
K
Karel Zak 已提交
6155 6156
}

6157
static char *
6158
vshReadline(vshControl *ctl ATTRIBUTE_UNUSED, const char *prompt)
6159
{
6160
    return readline(prompt);
6161 6162
}

6163
#else /* !USE_READLINE */
6164

6165
static int
6166
vshReadlineInit(vshControl *ctl ATTRIBUTE_UNUSED)
6167 6168 6169 6170 6171
{
    /* empty */
    return 0;
}

6172
static void
6173
vshReadlineDeinit(vshControl *ctl ATTRIBUTE_UNUSED)
6174 6175 6176 6177 6178
{
    /* empty */
}

static char *
6179
vshReadline(vshControl *ctl, const char *prompt)
6180 6181 6182 6183 6184
{
    char line[1024];
    char *r;
    int len;

6185 6186
    fputs(prompt, stdout);
    r = fgets(line, sizeof(line), stdin);
6187 6188 6189
    if (r == NULL) return NULL; /* EOF */

    /* Chomp trailing \n */
6190
    len = strlen(r);
6191 6192 6193
    if (len > 0 && r[len-1] == '\n')
        r[len-1] = '\0';

6194
    return vshStrdup(ctl, r);
6195 6196
}

6197
#endif /* !USE_READLINE */
6198

6199 6200 6201 6202 6203 6204
static void
vshDeinitTimer(int timer ATTRIBUTE_UNUSED, void *opaque ATTRIBUTE_UNUSED)
{
    /* nothing to be done here */
}

K
Karel Zak 已提交
6205
/*
J
Jim Meyering 已提交
6206
 * Deinitialize virsh
K
Karel Zak 已提交
6207
 */
E
Eric Blake 已提交
6208
static bool
6209
vshDeinit(vshControl *ctl)
6210
{
6211
    vshReadlineDeinit(ctl);
6212
    vshCloseLogFile(ctl);
6213
    VIR_FREE(ctl->name);
K
Karel Zak 已提交
6214
    if (ctl->conn) {
6215 6216 6217
        int ret;
        if ((ret = virConnectClose(ctl->conn)) != 0) {
            vshError(ctl, _("Failed to disconnect from the hypervisor, %d leaked reference(s)"), ret);
K
Karel Zak 已提交
6218 6219
        }
    }
D
Daniel P. Berrange 已提交
6220 6221
    virResetLastError();

J
Jiri Denemark 已提交
6222
    if (ctl->eventLoopStarted) {
6223 6224 6225 6226
        int timer;

        virMutexLock(&ctl->lock);
        ctl->quit = true;
J
Jiri Denemark 已提交
6227
        /* HACK: Add a dummy timeout to break event loop */
6228 6229 6230 6231 6232
        timer = virEventAddTimeout(0, vshDeinitTimer, NULL, NULL);
        virMutexUnlock(&ctl->lock);

        virThreadJoin(&ctl->eventLoop);

J
Jiri Denemark 已提交
6233 6234 6235 6236 6237 6238
        if (timer != -1)
            virEventRemoveTimeout(timer);

        ctl->eventLoopStarted = false;
    }

6239 6240
    virMutexDestroy(&ctl->lock);

E
Eric Blake 已提交
6241
    return true;
K
Karel Zak 已提交
6242
}
6243

K
Karel Zak 已提交
6244 6245 6246 6247
/*
 * Print usage
 */
static void
6248
vshUsage(void)
6249
{
6250
    const vshCmdGrp *grp;
6251
    const vshCmdDef *cmd;
6252

L
Lai Jiangshan 已提交
6253 6254
    fprintf(stdout, _("\n%s [options]... [<command_string>]"
                      "\n%s [options]... <command> [args...]\n\n"
6255
                      "  options:\n"
6256
                      "    -c | --connect=URI      hypervisor connection URI\n"
6257
                      "    -r | --readonly         connect readonly\n"
6258
                      "    -d | --debug=NUM        debug level [0-4]\n"
6259 6260 6261
                      "    -h | --help             this help\n"
                      "    -q | --quiet            quiet mode\n"
                      "    -t | --timing           print timing information\n"
6262 6263 6264 6265 6266
                      "    -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"
6267
                      "  commands (non interactive mode):\n\n"), progname, progname);
6268

6269
    for (grp = cmdGroups; grp->name; grp++) {
E
Eric Blake 已提交
6270 6271 6272 6273 6274
        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;
6275
            fprintf(stdout,
E
Eric Blake 已提交
6276 6277 6278
                    "    %-30s %s\n", cmd->name,
                    _(vshCmddefGetInfo(cmd, "help")));
        }
6279 6280 6281 6282 6283
        fprintf(stdout, "\n");
    }

    fprintf(stdout, "%s",
            _("\n  (specify help <group> for details about the commands in the group)\n"));
6284 6285 6286
    fprintf(stdout, "%s",
            _("\n  (specify help <command> for details about the command)\n\n"));
    return;
K
Karel Zak 已提交
6287 6288
}

6289 6290 6291 6292 6293 6294 6295 6296 6297 6298
/*
 * 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 已提交
6299 6300
    vshPrint(ctl, "%s", _("Compiled with support for:\n"));
    vshPrint(ctl, "%s", _(" Hypervisors:"));
6301 6302 6303
#ifdef WITH_QEMU
    vshPrint(ctl, " QEmu/KVM");
#endif
D
Doug Goldstein 已提交
6304 6305 6306
#ifdef WITH_LXC
    vshPrint(ctl, " LXC");
#endif
6307 6308 6309
#ifdef WITH_UML
    vshPrint(ctl, " UML");
#endif
D
Doug Goldstein 已提交
6310 6311 6312 6313 6314 6315
#ifdef WITH_XEN
    vshPrint(ctl, " Xen");
#endif
#ifdef WITH_LIBXL
    vshPrint(ctl, " LibXL");
#endif
6316 6317 6318
#ifdef WITH_OPENVZ
    vshPrint(ctl, " OpenVZ");
#endif
D
Doug Goldstein 已提交
6319 6320
#ifdef WITH_VMWARE
    vshPrint(ctl, " VMWare");
6321
#endif
D
Doug Goldstein 已提交
6322 6323
#ifdef WITH_PHYP
    vshPrint(ctl, " PHYP");
6324
#endif
D
Doug Goldstein 已提交
6325 6326
#ifdef WITH_VBOX
    vshPrint(ctl, " VirtualBox");
6327 6328 6329 6330
#endif
#ifdef WITH_ESX
    vshPrint(ctl, " ESX");
#endif
D
Doug Goldstein 已提交
6331 6332
#ifdef WITH_HYPERV
    vshPrint(ctl, " Hyper-V");
6333
#endif
D
Doug Goldstein 已提交
6334 6335
#ifdef WITH_XENAPI
    vshPrint(ctl, " XenAPI");
6336 6337 6338 6339 6340 6341
#endif
#ifdef WITH_TEST
    vshPrint(ctl, " Test");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
6342
    vshPrint(ctl, "%s", _(" Networking:"));
6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355
#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 已提交
6356
    vshPrint(ctl, " Interface");
6357 6358 6359 6360 6361 6362 6363 6364 6365
#endif
#ifdef WITH_NWFILTER
    vshPrint(ctl, " Nwfilter");
#endif
#ifdef WITH_VIRTUALPORT
    vshPrint(ctl, " VirtualPort");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
6366
    vshPrint(ctl, "%s", _(" Storage:"));
6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386
#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");
6387 6388 6389
#endif
#ifdef WITH_STORAGE_RBD
    vshPrint(ctl, " RBD");
6390 6391 6392
#endif
#ifdef WITH_STORAGE_SHEEPDOG
    vshPrint(ctl, " Sheepdog");
6393 6394 6395
#endif
    vshPrint(ctl, "\n");

6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525
    vshPrint(ctl, "%s", _(" Miscellaneous:"));
#ifdef WITH_NODE_DEVICES
    vshPrint(ctl, " Nodedev");
#endif
#ifdef WITH_SECDRIVER_APPARMOR
    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
#ifdef WITH_DTRACE_PROBES
    vshPrint(ctl, " DTrace");
#endif
#ifdef USE_READLINE
    vshPrint(ctl, " Readline");
#endif
#ifdef WITH_DRIVER_MODULES
    vshPrint(ctl, " Modular");
#endif
    vshPrint(ctl, "\n");
}

static bool
vshAllowedEscapeChar(char c)
{
    /* Allowed escape characters:
     * a-z A-Z @ [ \ ] ^ _
     */
    return ('a' <= c && c <= 'z') ||
        ('@' <= c && c <= '_');
}

/*
 * argv[]:  virsh [options] [command]
 *
 */
static bool
vshParseArgv(vshControl *ctl, int argc, char **argv)
{
    int arg, len;
    struct option opt[] = {
        {"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'},
        {"escape", required_argument, NULL, 'e'},
        {NULL, 0, NULL, 0}
    };

    /* 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. */
    while ((arg = getopt_long(argc, argv, "+d:hqtc:vVrl:e:", opt, NULL)) != -1) {
        switch (arg) {
        case 'd':
            if (virStrToLong_i(optarg, NULL, 10, &ctl->debug) < 0) {
                vshError(ctl, "%s", _("option -d takes a numeric argument"));
                exit(EXIT_FAILURE);
            }
            break;
        case 'h':
            vshUsage();
            exit(EXIT_SUCCESS);
            break;
        case 'q':
            ctl->quiet = true;
            break;
        case 't':
            ctl->timing = true;
            break;
        case 'c':
            ctl->name = vshStrdup(ctl, optarg);
            break;
        case 'v':
            if (STRNEQ_NULLABLE(optarg, "long")) {
                puts(VERSION);
                exit(EXIT_SUCCESS);
            }
            /* fall through */
        case 'V':
            vshShowVersion(ctl);
            exit(EXIT_SUCCESS);
        case 'r':
            ctl->readonly = true;
            break;
        case 'l':
            ctl->logfile = vshStrdup(ctl, optarg);
            break;
        case 'e':
            len = strlen(optarg);

            if ((len == 2 && *optarg == '^' &&
                 vshAllowedEscapeChar(optarg[1])) ||
                (len == 1 && *optarg != '^')) {
                ctl->escapeChar = optarg;
            } else {
                vshError(ctl, _("Invalid string '%s' for escape sequence"),
                         optarg);
                exit(EXIT_FAILURE);
            }
            break;
        default:
            vshError(ctl, _("unsupported option '-%c'. See --help."), arg);
            exit(EXIT_FAILURE);
        }
    }

    if (argc > optind) {
        /* parse command */
        ctl->imode = false;
        if (argc - optind == 1) {
            vshDebug(ctl, VSH_ERR_INFO, "commands: \"%s\"\n", argv[optind]);
            return vshCommandStringParse(ctl, argv[optind]);
        } else {
            return vshCommandArgvParse(ctl, argc - optind, argv + optind);
        }
    }
    return true;
}

6526 6527
#include "virsh-domain.c"

6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622
static const vshCmdDef domManagementCmds[] = {
    {"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},
    {"blkdeviotune", cmdBlkdeviotune, opts_blkdeviotune, info_blkdeviotune, 0},
    {"blkiotune", cmdBlkiotune, opts_blkiotune, info_blkiotune, 0},
    {"blockcopy", cmdBlockCopy, opts_block_copy, info_block_copy, 0},
    {"blockjob", cmdBlockJob, opts_block_job, info_block_job, 0},
    {"blockpull", cmdBlockPull, opts_block_pull, info_block_pull, 0},
    {"blockresize", cmdBlockResize, opts_block_resize, info_block_resize, 0},
    {"change-media", cmdChangeMedia, opts_change_media, info_change_media, 0},
#ifndef WIN32
    {"console", cmdConsole, opts_console, info_console, 0},
#endif
    {"cpu-baseline", cmdCPUBaseline, opts_cpu_baseline, info_cpu_baseline, 0},
    {"cpu-compare", cmdCPUCompare, opts_cpu_compare, info_cpu_compare, 0},
    {"cpu-stats", cmdCPUStats, opts_cpu_stats, info_cpu_stats, 0},
    {"create", cmdCreate, opts_create, info_create, 0},
    {"define", cmdDefine, opts_define, info_define, 0},
    {"desc", cmdDesc, opts_desc, info_desc, 0},
    {"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},
    {"domdisplay", cmdDomDisplay, opts_domdisplay, info_domdisplay, 0},
    {"domhostname", cmdDomHostname, opts_domhostname, info_domhostname, 0},
    {"domid", cmdDomid, opts_domid, info_domid, 0},
    {"domif-setlink", cmdDomIfSetLink, opts_domif_setlink, info_domif_setlink, 0},
    {"domiftune", cmdDomIftune, opts_domiftune, info_domiftune, 0},
    {"domjobabort", cmdDomjobabort, opts_domjobabort, info_domjobabort, 0},
    {"domjobinfo", cmdDomjobinfo, opts_domjobinfo, info_domjobinfo, 0},
    {"domname", cmdDomname, opts_domname, info_domname, 0},
    {"dompmsuspend", cmdDomPMSuspend,
     opts_dom_pm_suspend, info_dom_pm_suspend, 0},
    {"dompmwakeup", cmdDomPMWakeup,
     opts_dom_pm_wakeup, info_dom_pm_wakeup, 0},
    {"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},
    {"send-key", cmdSendKey, opts_send_key, info_send_key, 0},
    {"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},
    {"migrate-setspeed", cmdMigrateSetMaxSpeed,
     opts_migrate_setspeed, info_migrate_setspeed, 0},
    {"migrate-getspeed", cmdMigrateGetMaxSpeed,
     opts_migrate_getspeed, info_migrate_getspeed, 0},
    {"numatune", cmdNumatune, opts_numatune, info_numatune, 0},
    {"reboot", cmdReboot, opts_reboot, info_reboot, 0},
    {"reset", cmdReset, opts_reset, info_reset, 0},
    {"restore", cmdRestore, opts_restore, info_restore, 0},
    {"resume", cmdResume, opts_resume, info_resume, 0},
    {"save", cmdSave, opts_save, info_save, 0},
    {"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},
    {"schedinfo", cmdSchedinfo, opts_schedinfo, info_schedinfo, 0},
    {"screenshot", cmdScreenshot, opts_screenshot, info_screenshot, 0},
    {"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},
    {"vcpupin", cmdVcpuPin, opts_vcpupin, info_vcpupin, 0},
    {"vncdisplay", cmdVNCDisplay, opts_vncdisplay, info_vncdisplay, 0},
    {NULL, NULL, NULL, NULL, 0}
};

6623 6624
#include "virsh-domain-monitor.c"

6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640
static const vshCmdDef domMonitoringCmds[] = {
    {"domblkerror", cmdDomBlkError, opts_domblkerror, info_domblkerror, 0},
    {"domblkinfo", cmdDomblkinfo, opts_domblkinfo, info_domblkinfo, 0},
    {"domblklist", cmdDomblklist, opts_domblklist, info_domblklist, 0},
    {"domblkstat", cmdDomblkstat, opts_domblkstat, info_domblkstat, 0},
    {"domcontrol", cmdDomControl, opts_domcontrol, info_domcontrol, 0},
    {"domif-getlink", cmdDomIfGetLink, opts_domif_getlink, info_domif_getlink, 0},
    {"domiflist", cmdDomiflist, opts_domiflist, info_domiflist, 0},
    {"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}
};

6641 6642
#include "virsh-pool.c"

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
static const vshCmdDef storagePoolCmds[] = {
    {"find-storage-pool-sources-as", cmdPoolDiscoverSourcesAs,
     opts_find_storage_pool_sources_as, info_find_storage_pool_sources_as, 0},
    {"find-storage-pool-sources", cmdPoolDiscoverSources,
     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}
};

6670 6671
#include "virsh-volume.c"

6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693
static const vshCmdDef storageVolCmds[] = {
    {"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},
    {"vol-resize", cmdVolResize, opts_vol_resize, info_vol_resize, 0},
    {"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}
};

6694 6695
#include "virsh-network.c"

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
static const vshCmdDef networkCmds[] = {
    {"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}
};

static const vshCmdDef nodedevCmds[] = {
    {"nodedev-create", cmdNodeDeviceCreate, opts_node_device_create,
     info_node_device_create, 0},
    {"nodedev-destroy", cmdNodeDeviceDestroy, opts_node_device_destroy,
     info_node_device_destroy, 0},
    {"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},
    {"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}
};

6738 6739
#include "virsh-interface.c"

6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770
static const vshCmdDef ifaceCmds[] = {
    {"iface-begin", cmdInterfaceBegin, opts_interface_begin,
     info_interface_begin, 0},
    {"iface-bridge", cmdInterfaceBridge, opts_interface_bridge,
     info_interface_bridge, 0},
    {"iface-commit", cmdInterfaceCommit, opts_interface_commit,
     info_interface_commit, 0},
    {"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},
    {"iface-rollback", cmdInterfaceRollback, opts_interface_rollback,
     info_interface_rollback, 0},
    {"iface-start", cmdInterfaceStart, opts_interface_start,
     info_interface_start, 0},
    {"iface-unbridge", cmdInterfaceUnbridge, opts_interface_unbridge,
     info_interface_unbridge, 0},
    {"iface-undefine", cmdInterfaceUndefine, opts_interface_undefine,
     info_interface_undefine, 0},
    {NULL, NULL, NULL, NULL, 0}
};
6771

6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784
static const vshCmdDef nwfilterCmds[] = {
    {"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}
};
6785

6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799
static const vshCmdDef secretCmds[] = {
    {"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}
};
6800

6801 6802 6803 6804 6805 6806 6807 6808 6809
static const vshCmdDef virshCmds[] = {
    {"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}
};
6810

6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833
static const vshCmdDef snapshotCmds[] = {
    {"snapshot-create", cmdSnapshotCreate, opts_snapshot_create,
     info_snapshot_create, 0},
    {"snapshot-create-as", cmdSnapshotCreateAs, opts_snapshot_create_as,
     info_snapshot_create_as, 0},
    {"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},
    {"snapshot-edit", cmdSnapshotEdit, opts_snapshot_edit,
     info_snapshot_edit, 0},
    {"snapshot-info", cmdSnapshotInfo, opts_snapshot_info,
     info_snapshot_info, 0},
    {"snapshot-list", cmdSnapshotList, opts_snapshot_list,
     info_snapshot_list, 0},
    {"snapshot-parent", cmdSnapshotParent, opts_snapshot_parent,
     info_snapshot_parent, 0},
    {"snapshot-revert", cmdDomainSnapshotRevert, opts_snapshot_revert,
     info_snapshot_revert, 0},
    {NULL, NULL, NULL, NULL, 0}
};
K
Karel Zak 已提交
6834

6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868
static const vshCmdDef hostAndHypervisorCmds[] = {
    {"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},
    {"nodecpustats", cmdNodeCpuStats, opts_node_cpustats, info_nodecpustats, 0},
    {"nodeinfo", cmdNodeinfo, NULL, info_nodeinfo, 0},
    {"nodememstats", cmdNodeMemStats, opts_node_memstats, info_nodememstats, 0},
    {"nodesuspend", cmdNodeSuspend, opts_node_suspend, info_nodesuspend, 0},
    {"qemu-attach", cmdQemuAttach, opts_qemu_attach, info_qemu_attach, 0},
    {"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},
    {"version", cmdVersion, opts_version, info_version, 0},
    {NULL, NULL, NULL, NULL, 0}
};

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 已提交
6869

6870 6871 6872 6873
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
6874
    char *defaultConn;
E
Eric Blake 已提交
6875
    bool ret = true;
K
Karel Zak 已提交
6876

6877 6878 6879
    memset(ctl, 0, sizeof(vshControl));
    ctl->imode = true;          /* default is interactive mode */
    ctl->log_fd = -1;           /* Initialize log file descriptor */
J
Jiri Denemark 已提交
6880
    ctl->debug = VSH_DEBUG_DEFAULT;
6881 6882
    ctl->escapeChar = CTRL_CLOSE_BRACKET;

6883

6884 6885
    if (!setlocale(LC_ALL, "")) {
        perror("setlocale");
6886
        /* failure to setup locale is not fatal */
6887
    }
6888
    if (!bindtextdomain(PACKAGE, LOCALEDIR)) {
6889
        perror("bindtextdomain");
E
Eric Blake 已提交
6890
        return EXIT_FAILURE;
6891
    }
6892
    if (!textdomain(PACKAGE)) {
6893
        perror("textdomain");
E
Eric Blake 已提交
6894
        return EXIT_FAILURE;
6895 6896
    }

6897 6898 6899 6900 6901
    if (virMutexInit(&ctl->lock) < 0) {
        vshError(ctl, "%s", _("Failed to initialize mutex"));
        return EXIT_FAILURE;
    }

6902 6903 6904 6905 6906
    if (virInitialize() < 0) {
        vshError(ctl, "%s", _("Failed to initialize libvirt"));
        return EXIT_FAILURE;
    }

6907
    if (!(progname = strrchr(argv[0], '/')))
K
Karel Zak 已提交
6908 6909 6910
        progname = argv[0];
    else
        progname++;
6911

6912
    if ((defaultConn = getenv("VIRSH_DEFAULT_CONNECT_URI"))) {
E
Eric Blake 已提交
6913
        ctl->name = vshStrdup(ctl, defaultConn);
6914 6915
    }

D
Daniel P. Berrange 已提交
6916 6917
    if (!vshParseArgv(ctl, argc, argv)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
6918
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
6919
    }
6920

D
Daniel P. Berrange 已提交
6921 6922
    if (!vshInit(ctl)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
6923
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
6924
    }
6925

K
Karel Zak 已提交
6926
    if (!ctl->imode) {
6927
        ret = vshCommandRun(ctl, ctl->cmd);
6928
    } else {
K
Karel Zak 已提交
6929 6930
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
6931
            vshPrint(ctl,
6932
                     _("Welcome to %s, the virtualization interactive terminal.\n\n"),
6933
                     progname);
J
Jim Meyering 已提交
6934
            vshPrint(ctl, "%s",
6935
                     _("Type:  'help' for help with commands\n"
6936
                       "       'quit' to quit\n\n"));
K
Karel Zak 已提交
6937
        }
6938 6939 6940 6941 6942 6943

        if (vshReadlineInit(ctl) < 0) {
            vshDeinit(ctl);
            exit(EXIT_FAILURE);
        }

K
Karel Zak 已提交
6944
        do {
6945
            const char *prompt = ctl->readonly ? VSH_PROMPT_RO : VSH_PROMPT_RW;
6946
            ctl->cmdstr =
6947
                vshReadline(ctl, prompt);
6948 6949
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
6950
            if (*ctl->cmdstr) {
6951
#if USE_READLINE
K
Karel Zak 已提交
6952
                add_history(ctl->cmdstr);
6953
#endif
6954
                if (vshCommandStringParse(ctl, ctl->cmdstr))
K
Karel Zak 已提交
6955 6956
                    vshCommandRun(ctl, ctl->cmd);
            }
6957
            VIR_FREE(ctl->cmdstr);
6958
        } while (ctl->imode);
K
Karel Zak 已提交
6959

6960 6961
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
6962
    }
6963

K
Karel Zak 已提交
6964 6965
    vshDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
6966
}