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

16
#define _GNU_SOURCE             /* isblank() */
K
Karel Zak 已提交
17

18 19
#include "libvirt/libvirt.h"
#include "libvirt/virterror.h"
20
#include <stdio.h>
K
Karel Zak 已提交
21 22 23
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
24
#include <unistd.h>
K
Karel Zak 已提交
25
#include <getopt.h>
26
#include <sys/types.h>
K
Karel Zak 已提交
27
#include <sys/time.h>
K
Karel Zak 已提交
28
#include <ctype.h>
29
#include <fcntl.h>
30
#include <locale.h>
K
Karel Zak 已提交
31

32 33 34 35
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>

K
Karel Zak 已提交
36 37 38 39
#include <readline/readline.h>
#include <readline/history.h>

#include "config.h"
40
#include "internal.h"
41
#include "console.h"
K
Karel Zak 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

static char *progname;

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

#define VSH_PROMPT_RW    "virsh # "
#define VSH_PROMPT_RO    "virsh > "

#define GETTIMEOFDAY(T) gettimeofday(T, NULL)
#define DIFF_MSEC(T, U) \
        ((((int) ((T)->tv_sec - (U)->tv_sec)) * 1000000.0 + \
          ((int) ((T)->tv_usec - (U)->tv_usec))) / 1000.0)

58 59 60 61
/*
 * The error handler for virtsh
 */
static void
62 63
virshErrorHandler(void *unused, virErrorPtr error)
{
64 65 66 67 68 69 70 71 72 73
    if ((unused != NULL) || (error == NULL))
        return;

    /* Suppress the VIR_ERR_NO_XEN error which fails as non-root */
    if ((error->code == VIR_ERR_NO_XEN) || (error->code == VIR_ERR_OK))
        return;

    virDefaultErrorFunc(error);
}

K
Karel Zak 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86
/*
 * virsh command line grammar:
 *
 *    command_line    =     <command>\n | <command>; <command>; ...
 *
 *    command         =    <keyword> <option> <data>
 *
 *    option          =     <bool_option> | <int_option> | <string_option>
 *    data            =     <string>
 *
 *    bool_option     =     --optionname
 *    int_option      =     --optionname <number>
 *    string_option   =     --optionname <string>
87
 *
88 89 90
 *    keyword         =     [a-zA-Z]
 *    number          =     [0-9]+
 *    string          =     [^[:blank:]] | "[[:alnum:]]"$
K
Karel Zak 已提交
91 92 93 94
 *
 */

/*
95
 * vshCmdOptType - command option type
96
 */
K
Karel Zak 已提交
97
typedef enum {
98 99 100 101 102
    VSH_OT_NONE = 0,            /* none */
    VSH_OT_BOOL,                /* boolean option */
    VSH_OT_STRING,              /* string option */
    VSH_OT_INT,                 /* int option */
    VSH_OT_DATA                 /* string data (as non-option) */
K
Karel Zak 已提交
103 104 105 106 107
} vshCmdOptType;

/*
 * Command Option Flags
 */
108 109
#define VSH_OFLAG_NONE    0     /* without flags */
#define VSH_OFLAG_REQ    (1 << 1)       /* option required */
K
Karel Zak 已提交
110 111 112 113 114 115 116 117

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

/*
 * vshCmdInfo -- information about command
 */
118 119 120
typedef struct {
    const char *name;           /* name of information */
    const char *data;           /* information */
K
Karel Zak 已提交
121 122 123 124 125
} vshCmdInfo;

/*
 * vshCmdOptDef - command option definition
 */
126 127 128 129 130
typedef struct {
    const char *name;           /* the name of option */
    vshCmdOptType type;         /* option type */
    int flag;                   /* flags */
    const char *help;           /* help string */
K
Karel Zak 已提交
131 132 133 134 135 136
} vshCmdOptDef;

/*
 * vshCmdOpt - command options
 */
typedef struct vshCmdOpt {
137 138 139
    vshCmdOptDef *def;          /* pointer to relevant option */
    char *data;                 /* allocated data */
    struct vshCmdOpt *next;
K
Karel Zak 已提交
140 141 142 143 144
} vshCmdOpt;

/*
 * vshCmdDef - command definition
 */
145 146 147 148 149
typedef struct {
    const char *name;
    int (*handler) (vshControl *, vshCmd *);    /* command handler */
    vshCmdOptDef *opts;         /* definition of command options */
    vshCmdInfo *info;           /* details about command */
K
Karel Zak 已提交
150 151 152 153 154 155
} vshCmdDef;

/*
 * vshCmd - parsed command
 */
typedef struct __vshCmd {
156 157 158
    vshCmdDef *def;             /* command definition */
    vshCmdOpt *opts;            /* list of command arguments */
    struct __vshCmd *next;      /* next command */
K
Karel Zak 已提交
159 160 161 162 163 164
} __vshCmd;

/*
 * vshControl
 */
typedef struct __vshControl {
K
Karel Zak 已提交
165
    char *name;                 /* connection name */
166 167 168 169 170 171 172 173
    virConnectPtr conn;         /* connection to hypervisor */
    vshCmd *cmd;                /* the current command */
    char *cmdstr;               /* string with command */
    uid_t uid;                  /* process owner */
    int imode;                  /* interactive mode? */
    int quiet;                  /* quiet mode */
    int debug;                  /* print debug messages? */
    int timing;                 /* print timing info? */
174 175 176
    int readonly;               /* connect readonly (first time only, not
                                 * during explicit connect command)
                                 */
K
Karel Zak 已提交
177
} __vshControl;
178

179

K
Karel Zak 已提交
180 181
static vshCmdDef commands[];

182 183
static void vshError(vshControl * ctl, int doexit, const char *format, ...)
    ATTRIBUTE_FORMAT(printf, 3, 4);
184 185 186
static int vshInit(vshControl * ctl);
static int vshDeinit(vshControl * ctl);
static void vshUsage(vshControl * ctl, const char *cmdname);
K
Karel Zak 已提交
187

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

190
static const char *vshCmddefGetInfo(vshCmdDef * cmd, const char *info);
K
Karel Zak 已提交
191
static vshCmdDef *vshCmddefSearch(const char *cmdname);
192
static int vshCmddefHelp(vshControl * ctl, const char *name, int withprog);
K
Karel Zak 已提交
193

194 195 196 197 198
static vshCmdOpt *vshCommandOpt(vshCmd * cmd, const char *name);
static int vshCommandOptInt(vshCmd * cmd, const char *name, int *found);
static char *vshCommandOptString(vshCmd * cmd, const char *name,
                                 int *found);
static int vshCommandOptBool(vshCmd * cmd, const char *name);
K
Karel Zak 已提交
199

200 201 202
#define VSH_BYID     (1 << 1)
#define VSH_BYUUID   (1 << 2)
#define VSH_BYNAME   (1 << 3)
K
Karel Zak 已提交
203 204

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

/* default is lookup by Id, Name and UUID */
208 209
#define vshCommandOptDomain(_ctl, _cmd, _optname, _name)            \
    vshCommandOptDomainBy(_ctl, _cmd, _optname, _name,              \
210 211
                          VSH_BYID|VSH_BYUUID|VSH_BYNAME)

212 213 214 215 216 217 218 219
static virNetworkPtr vshCommandOptNetworkBy(vshControl * ctl, vshCmd * cmd,
                            const char *optname, char **name, int flag);

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

K
Karel Zak 已提交
220 221
static void vshPrintExtra(vshControl * ctl, const char *format, ...);
static void vshDebug(vshControl * ctl, int level, const char *format, ...);
K
Karel Zak 已提交
222 223

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

K
Karel Zak 已提交
226
static const char *vshDomainStateToString(int state);
227
static const char *vshDomainVcpuStateToString(int state);
228 229
static int vshConnectionUsability(vshControl * ctl, virConnectPtr conn,
                                  int showerror);
K
Karel Zak 已提交
230

231 232 233 234 235 236 237 238 239
static void *_vshMalloc(vshControl * ctl, size_t sz, const char *filename, int line);
#define vshMalloc(_ctl, _sz)    _vshMalloc(_ctl, _sz, __FILE__, __LINE__)

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

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

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258

static int idsorter(const void *a, const void *b) {
  const int *ia = (const int *)a;
  const int *ib = (const int *)b;

  if (*ia > *ib)
    return 1;
  else if (*ia < *ib)
    return -1;
  return 0;
}
static int namesorter(const void *a, const void *b) {
  const char **sa = (const char**)a;
  const char **sb = (const char**)b;

  return strcasecmp(*sa, *sb);
}


K
Karel Zak 已提交
259 260 261 262 263 264
/* ---------------
 * Commands
 * ---------------
 */

/*
265
 * "help" command
K
Karel Zak 已提交
266 267
 */
static vshCmdInfo info_help[] = {
268
    {"syntax", "help [<command>]"},
269 270 271
    {"help", gettext_noop("print help")},
    {"desc", gettext_noop("Prints global help or command specific help.")},

272
    {NULL, NULL}
K
Karel Zak 已提交
273 274 275
};

static vshCmdOptDef opts_help[] = {
276 277
    {"command", VSH_OT_DATA, 0, "name of command"},
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
278 279 280
};

static int
281 282
cmdHelp(vshControl * ctl, vshCmd * cmd)
{
K
Karel Zak 已提交
283
    const char *cmdname = vshCommandOptString(cmd, "command", NULL);
K
Karel Zak 已提交
284 285 286

    if (!cmdname) {
        vshCmdDef *def;
287

288
        vshPrint(ctl, _("Commands:\n\n"));
289
        for (def = commands; def->name; def++)
K
Karel Zak 已提交
290
            vshPrint(ctl, "    %-15s %s\n", def->name,
291
                     _N(vshCmddefGetInfo(def, "help")));
K
Karel Zak 已提交
292 293 294 295 296
        return TRUE;
    }
    return vshCmddefHelp(ctl, cmdname, FALSE);
}

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
/*
 * "autostart" command
 */
static vshCmdInfo info_autostart[] = {
    {"syntax", "autostart [--disable] <domain>"},
    {"help", gettext_noop("autostart a domain")},
    {"desc",
     gettext_noop("Configure a domain to be automatically started at boot.")},
    {NULL, NULL}
};

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

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

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

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

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

    if (virDomainSetAutostart(dom, autostart) < 0) {
        vshError(ctl, FALSE, _("Failed to %smark domain %s as autostarted"),
                 autostart ? "" : "un", name);
        virDomainFree(dom);
        return FALSE;
    }

    vshPrint(ctl, _("Domain %s %smarked as autostarted\n"),
             name, autostart ? "" : "un");

    return TRUE;
}

K
Karel Zak 已提交
342
/*
343
 * "connect" command
K
Karel Zak 已提交
344 345
 */
static vshCmdInfo info_connect[] = {
K
Karel Zak 已提交
346
    {"syntax", "connect [name] [--readonly]"},
347
    {"help", gettext_noop("(re)connect to hypervisor")},
348
    {"desc",
349
     gettext_noop("Connect to local hypervisor. This is built-in command after shell start up.")},
350
    {NULL, NULL}
K
Karel Zak 已提交
351 352 353
};

static vshCmdOptDef opts_connect[] = {
354 355
    {"name",     VSH_OT_DATA, 0, gettext_noop("hypervisor connection URI")},
    {"readonly", VSH_OT_BOOL, 0, gettext_noop("read-only connection")},
356
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
357 358 359
};

static int
360 361
cmdConnect(vshControl * ctl, vshCmd * cmd)
{
K
Karel Zak 已提交
362
    int ro = vshCommandOptBool(cmd, "readonly");
363

K
Karel Zak 已提交
364
    if (ctl->conn) {
365 366
        if (virConnectClose(ctl->conn) != 0) {
            vshError(ctl, FALSE,
367
                     _("Failed to disconnect from the hypervisor"));
K
Karel Zak 已提交
368 369 370 371
            return FALSE;
        }
        ctl->conn = NULL;
    }
372

K
Karel Zak 已提交
373 374
    if (ctl->name)
        free(ctl->name);
375
    ctl->name = vshStrdup(ctl, vshCommandOptString(cmd, "name", NULL));
K
Karel Zak 已提交
376

377
    if (!ro) {
K
Karel Zak 已提交
378
        ctl->conn = virConnectOpen(ctl->name);
379 380
        ctl->readonly = 0;
    } else {
K
Karel Zak 已提交
381
        ctl->conn = virConnectOpenReadOnly(ctl->name);
382 383
        ctl->readonly = 1;
    }
K
Karel Zak 已提交
384 385

    if (!ctl->conn)
386
        vshError(ctl, FALSE, _("Failed to connect to the hypervisor"));
387

K
Karel Zak 已提交
388 389 390
    return ctl->conn ? TRUE : FALSE;
}

391
/*
392
 * "console" command
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
 */
static vshCmdInfo info_console[] = {
    {"syntax", "console <domain>"},
    {"help", gettext_noop("connect to the guest console")},
    {"desc",
     gettext_noop("Connect the virtual serial console for the guest")},
    {NULL, NULL}
};

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

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

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

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

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

    xml = xmlReadDoc((const xmlChar *) doc, "domain.xml", NULL,
428 429
                     XML_PARSE_NOENT | XML_PARSE_NONET |
                     XML_PARSE_NOWARNING);
430 431 432 433 434 435 436 437 438
    free(doc);
    if (!xml)
        goto cleanup;
    ctxt = xmlXPathNewContext(xml);
    if (!ctxt)
        goto cleanup;

    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/console/@tty)", ctxt);
    if ((obj != NULL) && ((obj->type == XPATH_STRING) &&
439
                          (obj->stringval != NULL) && (obj->stringval[0] != 0))) {
440
        if (vshRunConsole((const char *)obj->stringval) == 0)
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
            ret = TRUE;
    } else {
        vshPrintExtra(ctl, _("No console available for domain\n"));
    }
    xmlXPathFreeObject(obj);

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

K
Karel Zak 已提交
456 457 458 459
/*
 * "list" command
 */
static vshCmdInfo info_list[] = {
460
    {"syntax", "list [--inactive | --all]"},
461 462
    {"help", gettext_noop("list domains")},
    {"desc", gettext_noop("Returns list of domains.")},
463
    {NULL, NULL}
K
Karel Zak 已提交
464 465
};

466
static vshCmdOptDef opts_list[] = {
467 468
    {"inactive", VSH_OT_BOOL, 0, gettext_noop("list inactive domains")},
    {"all", VSH_OT_BOOL, 0, gettext_noop("list inactive & active domains")},
469 470 471
    {NULL, 0, 0, NULL}
};

K
Karel Zak 已提交
472 473

static int
474 475
cmdList(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
476 477 478 479
    int inactive = vshCommandOptBool(cmd, "inactive");
    int all = vshCommandOptBool(cmd, "all");
    int active = !inactive || all ? 1 : 0;
    int *ids = NULL, maxid = 0, i;
480
    char **names = NULL;
481 482
    int maxname = 0;
    inactive |= all;
K
Karel Zak 已提交
483 484 485

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

487
    if (active) {
488 489 490 491 492 493 494 495 496 497 498 499 500 501
        maxid = virConnectNumOfDomains(ctl->conn);
        if (maxid < 0) {
            vshError(ctl, FALSE, _("Failed to list active domains"));
            return FALSE;
        }
        if (maxid) {
            ids = vshMalloc(ctl, sizeof(int) * maxid);

            if ((maxid = virConnectListDomains(ctl->conn, &ids[0], maxid)) < 0) {
                vshError(ctl, FALSE, _("Failed to list active domains"));
                free(ids);
                return FALSE;
            }

502
            qsort(&ids[0], maxid, sizeof(int), idsorter);
503
        }
504 505
    }
    if (inactive) {
506 507 508 509 510 511
        maxname = virConnectNumOfDefinedDomains(ctl->conn);
        if (maxname < 0) {
            vshError(ctl, FALSE, _("Failed to list inactive domains"));
            if (ids)
                free(ids);
            return FALSE;
512
        }
513 514 515 516 517 518 519 520 521 522
        if (maxname) {
            names = vshMalloc(ctl, sizeof(char *) * maxname);

            if ((maxname = virConnectListDefinedDomains(ctl->conn, names, maxname)) < 0) {
                vshError(ctl, FALSE, _("Failed to list inactive domains"));
                if (ids)
                    free(ids);
                free(names);
                return FALSE;
            }
523

524
            qsort(&names[0], maxname, sizeof(char*), namesorter);
525
        }
526
    }
527
    vshPrintExtra(ctl, "%3s %-20s %s\n", _("Id"), _("Name"), _("State"));
K
Karel Zak 已提交
528
    vshPrintExtra(ctl, "----------------------------------\n");
529 530

    for (i = 0; i < maxid; i++) {
K
Karel Zak 已提交
531 532
        virDomainInfo info;
        virDomainPtr dom = virDomainLookupByID(ctl->conn, ids[i]);
533
        const char *state;
534 535

        /* this kind of work with domains is not atomic operation */
K
Karel Zak 已提交
536 537
        if (!dom)
            continue;
538 539 540 541 542

        if (virDomainGetInfo(dom, &info) < 0)
            state = _("no state");
        else
            state = _N(vshDomainStateToString(info.state));
543

K
Karel Zak 已提交
544
        vshPrint(ctl, "%3d %-20s %s\n",
545 546
                 virDomainGetID(dom),
                 virDomainGetName(dom),
547
                 state);
548
        virDomainFree(dom);
K
Karel Zak 已提交
549
    }
550 551 552
    for (i = 0; i < maxname; i++) {
        virDomainInfo info;
        virDomainPtr dom = virDomainLookupByName(ctl->conn, names[i]);
553
        const char *state;
554 555

        /* this kind of work with domains is not atomic operation */
556
        if (!dom) {
557
            free(names[i]);
558
            continue;
559
        }
560 561 562 563 564 565 566

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

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

568
        virDomainFree(dom);
569
        free(names[i]);
570
    }
571 572
    if (ids)
        free(ids);
573 574
    if (names)
        free(names);
K
Karel Zak 已提交
575 576 577 578
    return TRUE;
}

/*
K
Karel Zak 已提交
579
 * "domstate" command
K
Karel Zak 已提交
580
 */
K
Karel Zak 已提交
581 582
static vshCmdInfo info_domstate[] = {
    {"syntax", "domstate <domain>"},
583 584
    {"help", gettext_noop("domain state")},
    {"desc", gettext_noop("Returns state about a running domain.")},
585
    {NULL, NULL}
K
Karel Zak 已提交
586 587
};

K
Karel Zak 已提交
588
static vshCmdOptDef opts_domstate[] = {
589
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
590
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
591 592 593
};

static int
K
Karel Zak 已提交
594
cmdDomstate(vshControl * ctl, vshCmd * cmd)
595
{
596
    virDomainInfo info;
K
Karel Zak 已提交
597
    virDomainPtr dom;
K
Karel Zak 已提交
598
    int ret = TRUE;
599

K
Karel Zak 已提交
600 601
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
602

K
Karel Zak 已提交
603
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
K
Karel Zak 已提交
604
        return FALSE;
605 606

    if (virDomainGetInfo(dom, &info) == 0)
K
Karel Zak 已提交
607
        vshPrint(ctl, "%s\n",
608
                 _N(vshDomainStateToString(info.state)));
K
Karel Zak 已提交
609 610
    else
        ret = FALSE;
611

612 613 614 615 616 617 618 619
    virDomainFree(dom);
    return ret;
}

/*
 * "suspend" command
 */
static vshCmdInfo info_suspend[] = {
620
    {"syntax", "suspend <domain>"},
621 622
    {"help", gettext_noop("suspend a domain")},
    {"desc", gettext_noop("Suspend a running domain.")},
623
    {NULL, NULL}
624 625 626
};

static vshCmdOptDef opts_suspend[] = {
627
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
628
    {NULL, 0, 0, NULL}
629 630 631
};

static int
632 633
cmdSuspend(vshControl * ctl, vshCmd * cmd)
{
634
    virDomainPtr dom;
K
Karel Zak 已提交
635 636
    char *name;
    int ret = TRUE;
637

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

K
Karel Zak 已提交
641
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
642
        return FALSE;
643 644

    if (virDomainSuspend(dom) == 0) {
645
        vshPrint(ctl, _("Domain %s suspended\n"), name);
646
    } else {
647
        vshError(ctl, FALSE, _("Failed to suspend domain %s"), name);
648 649
        ret = FALSE;
    }
650

651 652 653 654
    virDomainFree(dom);
    return ret;
}

655 656 657 658 659
/*
 * "create" command
 */
static vshCmdInfo info_create[] = {
    {"syntax", "create a domain from an XML <file>"},
660 661
    {"help", gettext_noop("create a domain from an XML file")},
    {"desc", gettext_noop("Create a domain.")},
662 663 664 665
    {NULL, NULL}
};

static vshCmdOptDef opts_create[] = {
666
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file conatining an XML domain description")},
667 668 669 670 671 672 673 674 675 676
    {NULL, 0, 0, NULL}
};

static int
cmdCreate(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    char *from;
    int found;
    int ret = TRUE;
677
    char buffer[BUFSIZ];
678 679 680 681 682 683 684 685 686 687 688
    int fd, l;

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

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

    fd = open(from, O_RDONLY);
    if (fd < 0) {
689
        vshError(ctl, FALSE, _("Failed to read description file %s"), from);
690 691 692 693
        return(FALSE);
    }
    l = read(fd, &buffer[0], sizeof(buffer));
    if ((l <= 0) || (l >= (int) sizeof(buffer))) {
694
        vshError(ctl, FALSE, _("Failed to read description file %s"), from);
695 696 697 698 699 700
        close(fd);
        return(FALSE);
    }
    buffer[l] = 0;
    dom = virDomainCreateLinux(ctl->conn, &buffer[0], 0);
    if (dom != NULL) {
701
        vshPrint(ctl, _("Domain %s created from %s\n"),
702 703
                 virDomainGetName(dom), from);
    } else {
704
        vshError(ctl, FALSE, _("Failed to create domain from %s"), from);
705 706 707 708 709
        ret = FALSE;
    }
    return ret;
}

710 711 712 713 714
/*
 * "define" command
 */
static vshCmdInfo info_define[] = {
    {"syntax", "define a domain from an XML <file>"},
715 716
    {"help", gettext_noop("define (but don't start) a domain from an XML file")},
    {"desc", gettext_noop("Define a domain.")},
717 718 719 720
    {NULL, NULL}
};

static vshCmdOptDef opts_define[] = {
721
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file conatining an XML domain description")},
722 723 724 725 726 727 728 729 730 731
    {NULL, 0, 0, NULL}
};

static int
cmdDefine(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    char *from;
    int found;
    int ret = TRUE;
732
    char buffer[BUFSIZ];
733 734 735 736 737 738 739 740 741 742 743
    int fd, l;

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

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

    fd = open(from, O_RDONLY);
    if (fd < 0) {
744
        vshError(ctl, FALSE, _("Failed to read description file %s"), from);
745 746 747 748
        return(FALSE);
    }
    l = read(fd, &buffer[0], sizeof(buffer));
    if ((l <= 0) || (l >= (int) sizeof(buffer))) {
749
        vshError(ctl, FALSE, _("Failed to read description file %s"), from);
750 751 752 753 754 755
        close(fd);
        return(FALSE);
    }
    buffer[l] = 0;
    dom = virDomainDefineXML(ctl->conn, &buffer[0]);
    if (dom != NULL) {
756
        vshPrint(ctl, _("Domain %s defined from %s\n"),
757 758
                 virDomainGetName(dom), from);
    } else {
759
        vshError(ctl, FALSE, _("Failed to define domain from %s"), from);
760 761 762 763 764 765 766 767 768 769
        ret = FALSE;
    }
    return ret;
}

/*
 * "undefine" command
 */
static vshCmdInfo info_undefine[] = {
    {"syntax", "undefine <domain>"},
770 771
    {"help", gettext_noop("undefine an inactive domain")},
    {"desc", gettext_noop("Undefine the configuration for an inactive domain.")},
772 773 774 775
    {NULL, NULL}
};

static vshCmdOptDef opts_undefine[] = {
776
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name or uuid")},
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
    {NULL, 0, 0, NULL}
};

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

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

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

    if (virDomainUndefine(dom) == 0) {
794
        vshPrint(ctl, _("Domain %s has been undefined\n"), name);
795
    } else {
796
        vshError(ctl, FALSE, _("Failed to undefine domain %s"), name);
797 798 799 800 801 802 803 804 805 806 807
        ret = FALSE;
    }

    return ret;
}


/*
 * "start" command
 */
static vshCmdInfo info_start[] = {
808
    {"syntax", "start <domain>"},
809 810
    {"help", gettext_noop("start a (previously defined) inactive domain")},
    {"desc", gettext_noop("Start a domain.")},
811 812 813 814
    {NULL, NULL}
};

static vshCmdOptDef opts_start[] = {
815
    {"name", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("name of the inactive domain")},
816 817 818 819 820 821 822 823 824 825 826 827
    {NULL, 0, 0, NULL}
};

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

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

828
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "name", NULL, VSH_BYNAME)))
829 830 831
        return FALSE;

    if (virDomainGetID(dom) != (unsigned int)-1) {
832
        vshError(ctl, FALSE, _("Domain is already active"));
833 834 835 836
        return FALSE;
    }

    if (virDomainCreate(dom) == 0) {
837
        vshPrint(ctl, _("Domain %s started\n"),
838
                 virDomainGetName(dom));
839
    } else {
840 841
        vshError(ctl, FALSE, _("Failed to start domain %s"),
                 virDomainGetName(dom));
842 843 844 845 846
        ret = FALSE;
    }
    return ret;
}

847 848 849 850
/*
 * "save" command
 */
static vshCmdInfo info_save[] = {
851
    {"syntax", "save <domain> <file>"},
852 853
    {"help", gettext_noop("save a domain state to a file")},
    {"desc", gettext_noop("Save a running domain.")},
854
    {NULL, NULL}
855 856 857
};

static vshCmdOptDef opts_save[] = {
858 859
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("where to save the data")},
860
    {NULL, 0, 0, NULL}
861 862 863
};

static int
864 865
cmdSave(vshControl * ctl, vshCmd * cmd)
{
866 867 868 869
    virDomainPtr dom;
    char *name;
    char *to;
    int ret = TRUE;
870

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

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

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

    if (virDomainSave(dom, to) == 0) {
881
        vshPrint(ctl, _("Domain %s saved to %s\n"), name, to);
882
    } else {
883
        vshError(ctl, FALSE, _("Failed to save domain %s to %s"), name, to);
884 885
        ret = FALSE;
    }
886

887 888 889 890 891 892 893 894
    virDomainFree(dom);
    return ret;
}

/*
 * "restore" command
 */
static vshCmdInfo info_restore[] = {
895
    {"syntax", "restore a domain from <file>"},
896 897
    {"help", gettext_noop("restore a domain from a saved state in a file")},
    {"desc", gettext_noop("Restore a domain.")},
898
    {NULL, NULL}
899 900 901
};

static vshCmdOptDef opts_restore[] = {
902
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("the state to restore")},
903
    {NULL, 0, 0, NULL}
904 905 906
};

static int
907 908
cmdRestore(vshControl * ctl, vshCmd * cmd)
{
909 910 911
    char *from;
    int found;
    int ret = TRUE;
912

913 914 915 916 917 918
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

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

    if (virDomainRestore(ctl->conn, from) == 0) {
921
        vshPrint(ctl, _("Domain restored from %s\n"), from);
922
    } else {
923
        vshError(ctl, FALSE, _("Failed to restore domain from %s"), from);
924 925 926 927 928
        ret = FALSE;
    }
    return ret;
}

D
Daniel Veillard 已提交
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
/*
 * "dump" command
 */
static vshCmdInfo info_dump[] = {
    {"syntax", "dump <domain> <file>"},
    {"help", gettext_noop("dump the core of a domain to a file for analysis")},
    {"desc", gettext_noop("Core dump a domain.")},
    {NULL, NULL}
};

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

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

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

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

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

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

    virDomainFree(dom);
    return ret;
}

974 975 976 977
/*
 * "resume" command
 */
static vshCmdInfo info_resume[] = {
978
    {"syntax", "resume <domain>"},
979 980
    {"help", gettext_noop("resume a domain")},
    {"desc", gettext_noop("Resume a previously suspended domain.")},
981
    {NULL, NULL}
982 983 984
};

static vshCmdOptDef opts_resume[] = {
985
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
986
    {NULL, 0, 0, NULL}
987 988 989
};

static int
990 991
cmdResume(vshControl * ctl, vshCmd * cmd)
{
992
    virDomainPtr dom;
K
Karel Zak 已提交
993 994
    int ret = TRUE;
    char *name;
995

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

K
Karel Zak 已提交
999
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
1000
        return FALSE;
1001 1002

    if (virDomainResume(dom) == 0) {
1003
        vshPrint(ctl, _("Domain %s resumed\n"), name);
1004
    } else {
1005
        vshError(ctl, FALSE, _("Failed to resume domain %s"), name);
1006 1007
        ret = FALSE;
    }
1008

1009 1010 1011 1012
    virDomainFree(dom);
    return ret;
}

1013 1014 1015 1016
/*
 * "shutdown" command
 */
static vshCmdInfo info_shutdown[] = {
1017
    {"syntax", "shutdown <domain>"},
1018 1019
    {"help", gettext_noop("gracefully shutdown a domain")},
    {"desc", gettext_noop("Run shutdown in the target domain.")},
1020
    {NULL, NULL}
1021 1022 1023
};

static vshCmdOptDef opts_shutdown[] = {
1024
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1025
    {NULL, 0, 0, NULL}
1026 1027 1028
};

static int
1029 1030
cmdShutdown(vshControl * ctl, vshCmd * cmd)
{
1031 1032 1033
    virDomainPtr dom;
    int ret = TRUE;
    char *name;
1034

1035 1036 1037 1038 1039
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

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

    if (virDomainShutdown(dom) == 0) {
1042
        vshPrint(ctl, _("Domain %s is being shutdown\n"), name);
1043
    } else {
1044
        vshError(ctl, FALSE, _("Failed to shutdown domain %s"), name);
1045 1046
        ret = FALSE;
    }
1047

1048 1049 1050 1051
    virDomainFree(dom);
    return ret;
}

1052 1053 1054 1055 1056
/*
 * "reboot" command
 */
static vshCmdInfo info_reboot[] = {
    {"syntax", "reboot <domain>"},
1057 1058
    {"help", gettext_noop("reboot a domain")},
    {"desc", gettext_noop("Run a reboot command in the target domain.")},
1059 1060 1061 1062
    {NULL, NULL}
};

static vshCmdOptDef opts_reboot[] = {
1063
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
    {NULL, 0, 0, NULL}
};

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

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

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

    if (virDomainReboot(dom, 0) == 0) {
1081
        vshPrint(ctl, _("Domain %s is being rebooted\n"), name);
1082
    } else {
1083
        vshError(ctl, FALSE, _("Failed to reboot domain %s"), name);
1084 1085 1086 1087 1088 1089 1090
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

1091 1092 1093 1094
/*
 * "destroy" command
 */
static vshCmdInfo info_destroy[] = {
1095
    {"syntax", "destroy <domain>"},
1096 1097
    {"help", gettext_noop("destroy a domain")},
    {"desc", gettext_noop("Destroy a given domain.")},
1098
    {NULL, NULL}
1099 1100 1101
};

static vshCmdOptDef opts_destroy[] = {
1102
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1103
    {NULL, 0, 0, NULL}
1104 1105 1106
};

static int
1107 1108
cmdDestroy(vshControl * ctl, vshCmd * cmd)
{
1109
    virDomainPtr dom;
K
Karel Zak 已提交
1110 1111
    int ret = TRUE;
    char *name;
1112

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

K
Karel Zak 已提交
1116
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
1117
        return FALSE;
1118 1119

    if (virDomainDestroy(dom) == 0) {
1120
        vshPrint(ctl, _("Domain %s destroyed\n"), name);
1121
    } else {
1122
        vshError(ctl, FALSE, _("Failed to destroy domain %s"), name);
1123 1124 1125
        ret = FALSE;
        virDomainFree(dom);
    }
1126

K
Karel Zak 已提交
1127 1128 1129 1130
    return ret;
}

/*
1131
 * "dominfo" command
K
Karel Zak 已提交
1132
 */
1133 1134
static vshCmdInfo info_dominfo[] = {
    {"syntax", "dominfo <domain>"},
1135 1136
    {"help", gettext_noop("domain information")},
    {"desc", gettext_noop("Returns basic information about the domain.")},
1137
    {NULL, NULL}
K
Karel Zak 已提交
1138 1139
};

1140
static vshCmdOptDef opts_dominfo[] = {
1141
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1142
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
1143 1144 1145
};

static int
1146
cmdDominfo(vshControl * ctl, vshCmd * cmd)
1147
{
K
Karel Zak 已提交
1148 1149
    virDomainInfo info;
    virDomainPtr dom;
K
Karel Zak 已提交
1150
    int ret = TRUE;
1151
    unsigned int id;
1152
    char *str, uuid[VIR_UUID_STRING_BUFLEN];
1153

K
Karel Zak 已提交
1154 1155 1156
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

K
Karel Zak 已提交
1157
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
K
Karel Zak 已提交
1158
        return FALSE;
1159

1160 1161
    id = virDomainGetID(dom);
    if (id == ((unsigned int)-1))
1162
        vshPrint(ctl, "%-15s %s\n", _("Id:"), "-");
1163
    else
1164
        vshPrint(ctl, "%-15s %d\n", _("Id:"), id);
1165 1166
    vshPrint(ctl, "%-15s %s\n", _("Name:"), virDomainGetName(dom));

K
Karel Zak 已提交
1167
    if (virDomainGetUUIDString(dom, &uuid[0])==0)
1168
        vshPrint(ctl, "%-15s %s\n", _("UUID:"), uuid);
1169 1170

    if ((str = virDomainGetOSType(dom))) {
1171
        vshPrint(ctl, "%-15s %s\n", _("OS Type:"), str);
1172 1173 1174 1175
        free(str);
    }

    if (virDomainGetInfo(dom, &info) == 0) {
1176 1177
        vshPrint(ctl, "%-15s %s\n", _("State:"),
                 _N(vshDomainStateToString(info.state)));
1178

1179
        vshPrint(ctl, "%-15s %d\n", _("CPU(s):"), info.nrVirtCpu);
1180 1181

        if (info.cpuTime != 0) {
1182
            double cpuUsed = info.cpuTime;
1183

1184
            cpuUsed /= 1000000000.0;
1185

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

1189 1190
        if (info.maxMem != UINT_MAX)
            vshPrint(ctl, "%-15s %lu kB\n", _("Max memory:"),
1191
                 info.maxMem);
1192 1193 1194 1195
        else
            vshPrint(ctl, "%-15s %-15s\n", _("Max memory:"),
                 _("no limit"));

1196
        vshPrint(ctl, "%-15s %lu kB\n", _("Used memory:"),
1197 1198
                 info.memory);

K
Karel Zak 已提交
1199 1200 1201
    } else {
        ret = FALSE;
    }
1202

1203
    virDomainFree(dom);
K
Karel Zak 已提交
1204 1205 1206
    return ret;
}

1207 1208 1209 1210 1211
/*
 * "vcpuinfo" command
 */
static vshCmdInfo info_vcpuinfo[] = {
    {"syntax", "vcpuinfo <domain>"},
1212 1213
    {"help", gettext_noop("domain vcpu information")},
    {"desc", gettext_noop("Returns basic information about the domain virtual CPUs.")},
1214 1215 1216 1217
    {NULL, NULL}
};

static vshCmdOptDef opts_vcpuinfo[] = {
1218
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
    {NULL, 0, 0, NULL}
};

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

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

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

    if (virNodeGetInfo(ctl->conn, &nodeinfo) != 0) {
        virDomainFree(dom);
1242
        return FALSE;
1243 1244 1245 1246 1247 1248 1249
    }

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

1250
    cpuinfo = vshMalloc(ctl, sizeof(virVcpuInfo)*info.nrVirtCpu);
1251
    cpumaplen = VIR_CPU_MAPLEN(VIR_NODEINFO_MAXCPUS(nodeinfo));
1252
    cpumap = vshMalloc(ctl, info.nrVirtCpu * cpumaplen);
1253

1254 1255 1256
    if ((ncpus = virDomainGetVcpus(dom,
                                   cpuinfo, info.nrVirtCpu,
                                   cpumap, cpumaplen)) >= 0) {
1257
        int n;
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
        for (n = 0 ; n < ncpus ; n++) {
            unsigned int m;
            vshPrint(ctl, "%-15s %d\n", _("VCPU:"), n);
            vshPrint(ctl, "%-15s %d\n", _("CPU:"), cpuinfo[n].cpu);
            vshPrint(ctl, "%-15s %s\n", _("State:"),
                     _N(vshDomainVcpuStateToString(cpuinfo[n].state)));
            if (cpuinfo[n].cpuTime != 0) {
                double cpuUsed = cpuinfo[n].cpuTime;

                cpuUsed /= 1000000000.0;

                vshPrint(ctl, "%-15s %.1lfs\n", _("CPU time:"), cpuUsed);
            }
            vshPrint(ctl, "%-15s ", _("CPU Affinity:"));
            for (m = 0 ; m < VIR_NODEINFO_MAXCPUS(nodeinfo) ; m++) {
                vshPrint(ctl, "%c", VIR_CPU_USABLE(cpumap, cpumaplen, n, m) ? 'y' : '-');
            }
            vshPrint(ctl, "\n");
            if (n < (ncpus - 1)) {
                vshPrint(ctl, "\n");
            }
        }
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
    } else {
        ret = FALSE;
    }

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

/*
 * "vcpupin" command
 */
static vshCmdInfo info_vcpupin[] = {
    {"syntax", "vcpupin <domain>"},
1295 1296
    {"help", gettext_noop("control domain vcpu affinity")},
    {"desc", gettext_noop("Pin domain VCPUs to host physical CPUs.")},
1297 1298 1299 1300
    {NULL, NULL}
};

static vshCmdOptDef opts_vcpupin[] = {
1301 1302 1303
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"vcpu", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("vcpu number")},
    {"cpulist", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("host cpu number(s) (comma separated)")},
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
    {NULL, 0, 0, NULL}
};

static int
cmdVcpupin(vshControl * ctl, vshCmd * cmd)
{
    virDomainInfo info;
    virDomainPtr dom;
    virNodeInfo nodeinfo;
    int vcpu;
    char *cpulist;
    int ret = TRUE;
    int vcpufound = 0;
    unsigned char *cpumap;
    int cpumaplen;

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

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

    vcpu = vshCommandOptInt(cmd, "vcpu", &vcpufound);
    if (!vcpufound) {
        virDomainFree(dom);
        return FALSE;
    }

    if (!(cpulist = vshCommandOptString(cmd, "cpulist", NULL))) {
        virDomainFree(dom);
        return FALSE;
    }
1336

1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
    if (virNodeGetInfo(ctl->conn, &nodeinfo) != 0) {
        virDomainFree(dom);
        return FALSE;
    }

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

    if (vcpu >= info.nrVirtCpu) {
        virDomainFree(dom);
        return FALSE;
    }

    cpumaplen = VIR_CPU_MAPLEN(VIR_NODEINFO_MAXCPUS(nodeinfo));
1353
    cpumap = vshCalloc(ctl, 1, cpumaplen);
1354 1355 1356 1357 1358 1359

    do {
        unsigned int cpu = atoi(cpulist);

        if (cpu < VIR_NODEINFO_MAXCPUS(nodeinfo)) {
            VIR_USE_CPU(cpumap, cpu);
1360 1361 1362 1363 1364
        } else {
            vshError(ctl, FALSE, _("Physical CPU %d doesn't exist."), cpu);
            free(cpumap);
            virDomainFree(dom);
            return FALSE;
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
        }
        cpulist = index(cpulist, ',');
        if (cpulist)
            cpulist++;
    } while (cpulist);

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

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

1380 1381 1382 1383 1384
/*
 * "setvcpus" command
 */
static vshCmdInfo info_setvcpus[] = {
    {"syntax", "setvcpus <domain> <count>"},
1385 1386
    {"help", gettext_noop("change number of virtual CPUs")},
    {"desc", gettext_noop("Change the number of virtual CPUs active in the guest domain.")},
1387 1388 1389 1390
    {NULL, NULL}
};

static vshCmdOptDef opts_setvcpus[] = {
1391 1392
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"count", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("number of virtual CPUs")},
1393 1394 1395 1396 1397 1398 1399 1400
    {NULL, 0, 0, NULL}
};

static int
cmdSetvcpus(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    int count;
1401
    int maxcpu;
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
    int ret = TRUE;

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

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

    count = vshCommandOptInt(cmd, "count", &count);
    if (!count) {
        virDomainFree(dom);
        return FALSE;
    }

1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
    maxcpu = virDomainGetMaxVcpus(dom);
    if (!maxcpu) {
        virDomainFree(dom);
        return FALSE;
    }

    if (count > maxcpu) {
        vshError(ctl, FALSE, _("Too many virtual CPU's."));
        virDomainFree(dom);
        return FALSE;
    }

1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
    if (virDomainSetVcpus(dom, count) != 0) {
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

/*
 * "setmemory" command
 */
static vshCmdInfo info_setmem[] = {
1440
    {"syntax", "setmem <domain> <kilobytes>"},
1441 1442
    {"help", gettext_noop("change memory allocation")},
    {"desc", gettext_noop("Change the current memory allocation in the guest domain.")},
1443 1444 1445 1446
    {NULL, NULL}
};

static vshCmdOptDef opts_setmem[] = {
1447
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1448
    {"kilobytes", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("number of kilobytes of memory")},
1449 1450 1451 1452 1453 1454 1455
    {NULL, 0, 0, NULL}
};

static int
cmdSetmem(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
1456
    int kilobytes;
1457 1458 1459 1460 1461 1462 1463 1464
    int ret = TRUE;

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

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

1465 1466
    kilobytes = vshCommandOptInt(cmd, "kilobytes", &kilobytes);
    if (kilobytes <= 0) {
1467
        virDomainFree(dom);
1468
        vshError(ctl, FALSE, _("Invalid value of %d for memory size"), kilobytes);
1469 1470 1471
        return FALSE;
    }

1472
    if (virDomainSetMemory(dom, kilobytes) != 0) {
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

/*
 * "setmaxmem" command
 */
static vshCmdInfo info_setmaxmem[] = {
1484
    {"syntax", "setmaxmem <domain> <kilobytes>"},
1485 1486
    {"help", gettext_noop("change maximum memory limit")},
    {"desc", gettext_noop("Change the maximum memory allocation limit in the guest domain.")},
1487 1488 1489 1490
    {NULL, NULL}
};

static vshCmdOptDef opts_setmaxmem[] = {
1491
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1492
    {"kilobytes", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("maxmimum memory limit in kilobytes")},
1493 1494 1495 1496 1497 1498 1499
    {NULL, 0, 0, NULL}
};

static int
cmdSetmaxmem(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
1500
    int kilobytes;
1501 1502 1503 1504 1505 1506 1507 1508
    int ret = TRUE;

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

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

1509 1510
    kilobytes = vshCommandOptInt(cmd, "kilobytes", &kilobytes);
    if (kilobytes <= 0) {
1511
        virDomainFree(dom);
1512
        vshError(ctl, FALSE, _("Invalid value of %d for memory size"), kilobytes);
1513 1514 1515
        return FALSE;
    }

1516
    if (virDomainSetMaxMemory(dom, kilobytes) != 0) {
1517 1518 1519 1520 1521 1522 1523
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

1524 1525 1526 1527 1528
/*
 * "nodeinfo" command
 */
static vshCmdInfo info_nodeinfo[] = {
    {"syntax", "nodeinfo"},
1529 1530
    {"help", gettext_noop("node information")},
    {"desc", gettext_noop("Returns basic information about the node.")},
1531 1532 1533 1534 1535 1536 1537
    {NULL, NULL}
};

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

1539 1540 1541 1542
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

    if (virNodeGetInfo(ctl->conn, &info) < 0) {
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
        vshError(ctl, FALSE, _("failed to get node information"));
        return FALSE;
    }
    vshPrint(ctl, "%-20s %s\n", _("CPU model:"), info.model);
    vshPrint(ctl, "%-20s %d\n", _("CPU(s):"), info.cpus);
    vshPrint(ctl, "%-20s %d MHz\n", _("CPU frequency:"), info.mhz);
    vshPrint(ctl, "%-20s %d\n", _("CPU socket(s):"), info.sockets);
    vshPrint(ctl, "%-20s %d\n", _("Core(s) per socket:"), info.cores);
    vshPrint(ctl, "%-20s %d\n", _("Thread(s) per core:"), info.threads);
    vshPrint(ctl, "%-20s %d\n", _("NUMA cell(s):"), info.nodes);
    vshPrint(ctl, "%-20s %lu kB\n", _("Memory size:"), info.memory);

1555 1556 1557
    return TRUE;
}

1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
/*
 * "capabilities" command
 */
static vshCmdInfo info_capabilities[] = {
    {"syntax", "capabilities"},
    {"help", gettext_noop("capabilities")},
    {"desc", gettext_noop("Returns capabilities of hypervisor/driver.")},
    {NULL, NULL}
};

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

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

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

    return TRUE;
}

1585 1586 1587 1588
/*
 * "dumpxml" command
 */
static vshCmdInfo info_dumpxml[] = {
1589
    {"syntax", "dumpxml <name>"},
1590 1591
    {"help", gettext_noop("domain information in XML")},
    {"desc", gettext_noop("Ouput the domain information as an XML dump to stdout.")},
1592
    {NULL, NULL}
1593 1594 1595
};

static vshCmdOptDef opts_dumpxml[] = {
1596
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1597
    {NULL, 0, 0, NULL}
1598 1599 1600
};

static int
1601 1602
cmdDumpXML(vshControl * ctl, vshCmd * cmd)
{
1603
    virDomainPtr dom;
K
Karel Zak 已提交
1604
    int ret = TRUE;
1605
    char *dump;
1606

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

K
Karel Zak 已提交
1610
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
1611
        return FALSE;
1612

1613 1614 1615 1616 1617 1618 1619
    dump = virDomainGetXMLDesc(dom, 0);
    if (dump != NULL) {
        printf("%s", dump);
        free(dump);
    } else {
        ret = FALSE;
    }
1620

1621 1622 1623 1624
    virDomainFree(dom);
    return ret;
}

K
Karel Zak 已提交
1625
/*
K
Karel Zak 已提交
1626
 * "domname" command
K
Karel Zak 已提交
1627
 */
K
Karel Zak 已提交
1628
static vshCmdInfo info_domname[] = {
K
Karel Zak 已提交
1629
    {"syntax", "domname <domain>"},
1630
    {"help", gettext_noop("convert a domain id or UUID to domain name")},
1631
    {NULL, NULL}
K
Karel Zak 已提交
1632 1633
};

K
Karel Zak 已提交
1634
static vshCmdOptDef opts_domname[] = {
1635
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain id or uuid")},
1636
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
1637 1638 1639
};

static int
K
Karel Zak 已提交
1640
cmdDomname(vshControl * ctl, vshCmd * cmd)
1641
{
K
Karel Zak 已提交
1642 1643 1644 1645
    virDomainPtr dom;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
1646
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "domain", NULL,
1647
                                      VSH_BYID|VSH_BYUUID)))
K
Karel Zak 已提交
1648
        return FALSE;
1649

K
Karel Zak 已提交
1650 1651
    vshPrint(ctl, "%s\n", virDomainGetName(dom));
    virDomainFree(dom);
K
Karel Zak 已提交
1652 1653 1654 1655
    return TRUE;
}

/*
K
Karel Zak 已提交
1656
 * "domid" command
K
Karel Zak 已提交
1657
 */
K
Karel Zak 已提交
1658
static vshCmdInfo info_domid[] = {
K
Karel Zak 已提交
1659
    {"syntax", "domid <domain>"},
1660
    {"help", gettext_noop("convert a domain name or UUID to domain id")},
1661
    {NULL, NULL}
K
Karel Zak 已提交
1662 1663
};

K
Karel Zak 已提交
1664
static vshCmdOptDef opts_domid[] = {
1665
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name or uuid")},
1666
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
1667 1668 1669
};

static int
K
Karel Zak 已提交
1670
cmdDomid(vshControl * ctl, vshCmd * cmd)
1671
{
1672
    virDomainPtr dom;
1673
    unsigned int id;
K
Karel Zak 已提交
1674 1675 1676

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
1677
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "domain", NULL,
1678
                                      VSH_BYNAME|VSH_BYUUID)))
K
Karel Zak 已提交
1679
        return FALSE;
1680

1681 1682
    id = virDomainGetID(dom);
    if (id == ((unsigned int)-1))
1683
        vshPrint(ctl, "%s\n", "-");
1684
    else
1685
        vshPrint(ctl, "%d\n", id);
K
Karel Zak 已提交
1686 1687 1688
    virDomainFree(dom);
    return TRUE;
}
1689

K
Karel Zak 已提交
1690 1691 1692 1693 1694
/*
 * "domuuid" command
 */
static vshCmdInfo info_domuuid[] = {
    {"syntax", "domuuid <domain>"},
1695
    {"help", gettext_noop("convert a domain name or id to domain UUID")},
K
Karel Zak 已提交
1696 1697 1698 1699
    {NULL, NULL}
};

static vshCmdOptDef opts_domuuid[] = {
1700
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain id or name")},
K
Karel Zak 已提交
1701 1702 1703 1704 1705 1706 1707
    {NULL, 0, 0, NULL}
};

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

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
K
Karel Zak 已提交
1711
        return FALSE;
1712
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "domain", NULL,
1713
                                      VSH_BYNAME|VSH_BYID)))
K
Karel Zak 已提交
1714
        return FALSE;
1715

K
Karel Zak 已提交
1716 1717 1718
    if (virDomainGetUUIDString(dom, uuid) != -1)
        vshPrint(ctl, "%s\n", uuid);
    else
1719 1720
        vshError(ctl, FALSE, _("failed to get domain UUID"));

K
Karel Zak 已提交
1721 1722 1723
    return TRUE;
}

1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
/*
 * "net-autostart" command
 */
static vshCmdInfo info_network_autostart[] = {
    {"syntax", "net-autostart [--disable] <network>"},
    {"help", gettext_noop("autostart a network")},
    {"desc",
     gettext_noop("Configure a network to be automatically started at boot.")},
    {NULL, NULL}
};

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

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

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

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

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

    if (virNetworkSetAutostart(network, autostart) < 0) {
        vshError(ctl, FALSE, _("Failed to %smark network %s as autostarted"),
                 autostart ? "" : "un", name);
        virNetworkFree(network);
        return FALSE;
    }

    vshPrint(ctl, _("Network %s %smarked as autostarted\n"),
             name, autostart ? "" : "un");

    return TRUE;
}
K
Karel Zak 已提交
1768

1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
/*
 * "net-create" command
 */
static vshCmdInfo info_network_create[] = {
    {"syntax", "create a network from an XML <file>"},
    {"help", gettext_noop("create a network from an XML file")},
    {"desc", gettext_noop("Create a network.")},
    {NULL, NULL}
};

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

static int
cmdNetworkCreate(vshControl * ctl, vshCmd * cmd)
{
    virNetworkPtr network;
    char *from;
    int found;
    int ret = TRUE;
    char buffer[BUFSIZ];
    int fd, l;

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

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

    fd = open(from, O_RDONLY);
    if (fd < 0) {
        vshError(ctl, FALSE, _("Failed to read description file %s"), from);
        return(FALSE);
    }
    l = read(fd, &buffer[0], sizeof(buffer));
    if ((l <= 0) || (l >= (int) sizeof(buffer))) {
        vshError(ctl, FALSE, _("Failed to read description file %s"), from);
        close(fd);
        return(FALSE);
    }
    buffer[l] = 0;
    network = virNetworkCreateXML(ctl->conn, &buffer[0]);
    if (network != NULL) {
        vshPrint(ctl, _("Network %s created from %s\n"),
                 virNetworkGetName(network), from);
    } else {
        vshError(ctl, FALSE, _("Failed to create network from %s"), from);
        ret = FALSE;
    }
    return ret;
}


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

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

static int
cmdNetworkDefine(vshControl * ctl, vshCmd * cmd)
{
    virNetworkPtr network;
    char *from;
    int found;
    int ret = TRUE;
    char buffer[BUFSIZ];
    int fd, l;

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

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

    fd = open(from, O_RDONLY);
    if (fd < 0) {
        vshError(ctl, FALSE, _("Failed to read description file %s"), from);
        return(FALSE);
    }
    l = read(fd, &buffer[0], sizeof(buffer));
    if ((l <= 0) || (l >= (int) sizeof(buffer))) {
        vshError(ctl, FALSE, _("Failed to read description file %s"), from);
        close(fd);
        return(FALSE);
    }
    buffer[l] = 0;
    network = virNetworkDefineXML(ctl->conn, &buffer[0]);
    if (network != NULL) {
        vshPrint(ctl, _("Network %s defined from %s\n"),
                 virNetworkGetName(network), from);
    } else {
        vshError(ctl, FALSE, _("Failed to define network from %s"), from);
        ret = FALSE;
    }
    return ret;
}


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

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

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

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

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

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

    return ret;
}


/*
 * "net-dumpxml" command
 */
static vshCmdInfo info_network_dumpxml[] = {
    {"syntax", "net-dumpxml <name>"},
    {"help", gettext_noop("network information in XML")},
    {"desc", gettext_noop("Ouput the network information as an XML dump to stdout.")},
    {NULL, NULL}
};

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

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

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

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

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

    virNetworkFree(network);
    return ret;
}


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

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

static int
cmdNetworkList(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
    int inactive = vshCommandOptBool(cmd, "inactive");
    int all = vshCommandOptBool(cmd, "all");
    int active = !inactive || all ? 1 : 0;
    int maxactive = 0, maxinactive = 0, i;
1985
    char **activeNames = NULL, **inactiveNames = NULL;
1986 1987 1988 1989 1990 1991
    inactive |= all;

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

    if (active) {
1992 1993 1994 1995
        maxactive = virConnectNumOfNetworks(ctl->conn);
        if (maxactive < 0) {
            vshError(ctl, FALSE, _("Failed to list active networks"));
            return FALSE;
1996
        }
1997
        if (maxactive) {
1998
            activeNames = vshMalloc(ctl, sizeof(char *) * maxactive);
1999

2000 2001
            if ((maxactive = virConnectListNetworks(ctl->conn, activeNames,
	                                            maxactive)) < 0) {
2002 2003 2004 2005
                vshError(ctl, FALSE, _("Failed to list active networks"));
                free(activeNames);
                return FALSE;
            }
2006

2007
            qsort(&activeNames[0], maxactive, sizeof(char *), namesorter);
2008
        }
2009 2010
    }
    if (inactive) {
2011 2012 2013 2014 2015 2016
        maxinactive = virConnectNumOfDefinedNetworks(ctl->conn);
        if (maxinactive < 0) {
            vshError(ctl, FALSE, _("Failed to list inactive networks"));
            if (activeNames)
                free(activeNames);
            return FALSE;
2017
        }
2018 2019 2020 2021 2022 2023 2024 2025 2026 2027
        if (maxinactive) {
            inactiveNames = vshMalloc(ctl, sizeof(char *) * maxinactive);

            if ((maxinactive = virConnectListDefinedNetworks(ctl->conn, inactiveNames, maxinactive)) < 0) {
                vshError(ctl, FALSE, _("Failed to list inactive networks"));
                if (activeNames)
                    free(activeNames);
                free(inactiveNames);
                return FALSE;
            }
2028

2029 2030
            qsort(&inactiveNames[0], maxinactive, sizeof(char*), namesorter);
        }
2031
    }
2032 2033
    vshPrintExtra(ctl, "%-20s %-10s %-10s\n", _("Name"), _("State"), _("Autostart"));
    vshPrintExtra(ctl, "-----------------------------------------\n");
2034 2035 2036

    for (i = 0; i < maxactive; i++) {
        virNetworkPtr network = virNetworkLookupByName(ctl->conn, activeNames[i]);
2037 2038
        const char *autostartStr;
        int autostart = 0;
2039 2040 2041 2042 2043

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

2046 2047 2048 2049 2050 2051 2052 2053 2054
        if (virNetworkGetAutostart(network, &autostart) < 0)
            autostartStr = _("no autostart");
        else
            autostartStr = autostart ? "yes" : "no";

        vshPrint(ctl, "%-20s %-10s %-10s\n",
                 virNetworkGetName(network),
                 _("active"),
                 autostartStr);
2055 2056 2057 2058 2059
        virNetworkFree(network);
        free(activeNames[i]);
    }
    for (i = 0; i < maxinactive; i++) {
        virNetworkPtr network = virNetworkLookupByName(ctl->conn, inactiveNames[i]);
2060 2061
        const char *autostartStr;
        int autostart = 0;
2062 2063 2064 2065 2066

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

2069 2070 2071 2072 2073 2074 2075 2076 2077
        if (virNetworkGetAutostart(network, &autostart) < 0)
            autostartStr = _("no autostart");
        else
            autostartStr = autostart ? "yes" : "no";

        vshPrint(ctl, "%-20s %s %s\n",
                 inactiveNames[i],
                 _("inactive"),
                 autostartStr);
2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144

        virNetworkFree(network);
        free(inactiveNames[i]);
    }
    if (activeNames)
        free(activeNames);
    if (inactiveNames)
        free(inactiveNames);
    return TRUE;
}


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

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

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

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
    if (!(network = vshCommandOptNetworkBy(ctl, cmd, "network", NULL,
					   VSH_BYUUID)))
        return FALSE;

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


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

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

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

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

2145 2146
    if (!(network = vshCommandOptNetworkBy(ctl, cmd, "name", NULL, VSH_BYNAME)))
         return FALSE;
2147 2148 2149

    if (virNetworkCreate(network) == 0) {
        vshPrint(ctl, _("Network %s started\n"),
2150
                 virNetworkGetName(network));
2151
    } else {
2152 2153
        vshError(ctl, FALSE, _("Failed to start network %s"),
                 virNetworkGetName(network));
2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
        ret = FALSE;
    }
    return ret;
}


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

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

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

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

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

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

    return ret;
}


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

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

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

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

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

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

    return TRUE;
}


2235 2236 2237 2238
/*
 * "version" command
 */
static vshCmdInfo info_version[] = {
2239
    {"syntax", "version"},
2240 2241
    {"help", gettext_noop("show version")},
    {"desc", gettext_noop("Display the system version information.")},
2242
    {NULL, NULL}
2243 2244 2245 2246
};


static int
2247 2248
cmdVersion(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
2249 2250
    unsigned long hvVersion;
    const char *hvType;
2251 2252 2253 2254 2255 2256 2257
    unsigned long libVersion;
    unsigned long includeVersion;
    unsigned long apiVersion;
    int ret;
    unsigned int major;
    unsigned int minor;
    unsigned int rel;
2258 2259 2260

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

2262 2263
    hvType = virConnectGetType(ctl->conn);
    if (hvType == NULL) {
2264
        vshError(ctl, FALSE, _("failed to get hypervisor type"));
2265 2266 2267
        return FALSE;
    }

2268 2269 2270 2271 2272
    includeVersion = LIBVIR_VERSION_NUMBER;
    major = includeVersion / 1000000;
    includeVersion %= 1000000;
    minor = includeVersion / 1000;
    rel = includeVersion % 1000;
2273
    vshPrint(ctl, _("Compiled against library: libvir %d.%d.%d\n"),
2274 2275 2276 2277
             major, minor, rel);

    ret = virGetVersion(&libVersion, hvType, &apiVersion);
    if (ret < 0) {
2278
        vshError(ctl, FALSE, _("failed to get the library version"));
2279 2280 2281 2282 2283 2284
        return FALSE;
    }
    major = libVersion / 1000000;
    libVersion %= 1000000;
    minor = libVersion / 1000;
    rel = libVersion % 1000;
2285
    vshPrint(ctl, _("Using library: libvir %d.%d.%d\n"),
2286
             major, minor, rel);
2287

2288 2289 2290 2291
    major = apiVersion / 1000000;
    apiVersion %= 1000000;
    minor = apiVersion / 1000;
    rel = apiVersion % 1000;
2292
    vshPrint(ctl, _("Using API: %s %d.%d.%d\n"), hvType,
2293 2294
             major, minor, rel);

2295
    ret = virConnectGetVersion(ctl->conn, &hvVersion);
2296
    if (ret < 0) {
2297
        vshError(ctl, FALSE, _("failed to get the hypervisor version"));
2298 2299 2300
        return FALSE;
    }
    if (hvVersion == 0) {
K
Karel Zak 已提交
2301
        vshPrint(ctl,
2302
                 _("Cannot extract running %s hypervisor version\n"), hvType);
2303
    } else {
2304
        major = hvVersion / 1000000;
2305
        hvVersion %= 1000000;
2306 2307
        minor = hvVersion / 1000;
        rel = hvVersion % 1000;
2308

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

2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348
/*
 * "dumpxml" command
 */
static vshCmdInfo info_vncdisplay[] = {
    {"syntax", "vncdisplay <domain>"},
    {"help", gettext_noop("vnc display")},
    {"desc", gettext_noop("Ouput the IP address and port number for the VNC display.")},
    {NULL, NULL}
};

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

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

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

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

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

    xml = xmlReadDoc((const xmlChar *) doc, "domain.xml", NULL,
2352 2353
                     XML_PARSE_NOENT | XML_PARSE_NONET |
                     XML_PARSE_NOWARNING);
2354 2355 2356 2357 2358 2359 2360 2361 2362
    free(doc);
    if (!xml)
        goto cleanup;
    ctxt = xmlXPathNewContext(xml);
    if (!ctxt)
        goto cleanup;

    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/graphics[@type='vnc']/@port)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
2363
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
2364 2365 2366 2367
        goto cleanup;
    }
    port = strtol((const char *)obj->stringval, NULL, 10);
    if (port == -1) {
2368
        goto cleanup;
2369 2370 2371 2372 2373
    }
    xmlXPathFreeObject(obj);

    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/graphics[@type='vnc']/@listen)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
2374 2375
        (obj->stringval == NULL) || (obj->stringval[0] == 0) ||
        !strcmp((const char*)obj->stringval, "0.0.0.0")) {
2376 2377 2378 2379 2380 2381 2382 2383 2384
        vshPrint(ctl, ":%d\n", port-5900);
    } else {
        vshPrint(ctl, "%s:%d\n", (const char *)obj->stringval, port-5900);
    }
    xmlXPathFreeObject(obj);
    obj = NULL;

 cleanup:
    if (obj)
2385
        xmlXPathFreeObject(obj);
2386 2387 2388 2389 2390 2391 2392 2393 2394
    if (ctxt)
        xmlXPathFreeContext(ctxt);
    if (xml)
        xmlFreeDoc(xml);
    virDomainFree(dom);
    return ret;
}


K
Karel Zak 已提交
2395 2396 2397 2398
/*
 * "quit" command
 */
static vshCmdInfo info_quit[] = {
2399
    {"syntax", "quit"},
2400
    {"help", gettext_noop("quit this interactive terminal")},
2401
    {NULL, NULL}
K
Karel Zak 已提交
2402 2403 2404
};

static int
2405 2406
cmdQuit(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
2407 2408 2409 2410 2411 2412 2413 2414
    ctl->imode = FALSE;
    return TRUE;
}

/*
 * Commands
 */
static vshCmdDef commands[] = {
2415
    {"autostart", cmdAutostart, opts_autostart, info_autostart},
2416
    {"capabilities", cmdCapabilities, NULL, info_capabilities},
2417
    {"connect", cmdConnect, opts_connect, info_connect},
2418
    {"console", cmdConsole, opts_console, info_console},
2419
    {"create", cmdCreate, opts_create, info_create},
2420
    {"start", cmdStart, opts_start, info_start},
K
Karel Zak 已提交
2421
    {"destroy", cmdDestroy, opts_destroy, info_destroy},
2422
    {"define", cmdDefine, opts_define, info_define},
K
Karel Zak 已提交
2423
    {"domid", cmdDomid, opts_domid, info_domid},
K
Karel Zak 已提交
2424
    {"domuuid", cmdDomuuid, opts_domuuid, info_domuuid},
2425
    {"dominfo", cmdDominfo, opts_dominfo, info_dominfo},
K
Karel Zak 已提交
2426 2427
    {"domname", cmdDomname, opts_domname, info_domname},
    {"domstate", cmdDomstate, opts_domstate, info_domstate},
2428
    {"dumpxml", cmdDumpXML, opts_dumpxml, info_dumpxml},
K
Karel Zak 已提交
2429
    {"help", cmdHelp, opts_help, info_help},
2430
    {"list", cmdList, opts_list, info_list},
2431
    {"net-autostart", cmdNetworkAutostart, opts_network_autostart, info_network_autostart},
2432 2433 2434 2435 2436 2437 2438 2439 2440
    {"net-create", cmdNetworkCreate, opts_network_create, info_network_create},
    {"net-define", cmdNetworkDefine, opts_network_define, info_network_define},
    {"net-destroy", cmdNetworkDestroy, opts_network_destroy, info_network_destroy},
    {"net-dumpxml", cmdNetworkDumpXML, opts_network_dumpxml, info_network_dumpxml},
    {"net-list", cmdNetworkList, opts_network_list, info_network_list},
    {"net-name", cmdNetworkName, opts_network_name, info_network_name},
    {"net-start", cmdNetworkStart, opts_network_start, info_network_start},
    {"net-undefine", cmdNetworkUndefine, opts_network_undefine, info_network_undefine},
    {"net-uuid", cmdNetworkUuid, opts_network_uuid, info_network_uuid},
K
Karel Zak 已提交
2441 2442 2443 2444
    {"nodeinfo", cmdNodeinfo, NULL, info_nodeinfo},
    {"quit", cmdQuit, NULL, info_quit},
    {"reboot", cmdReboot, opts_reboot, info_reboot},
    {"restore", cmdRestore, opts_restore, info_restore},
2445 2446
    {"resume", cmdResume, opts_resume, info_resume},
    {"save", cmdSave, opts_save, info_save},
D
Daniel Veillard 已提交
2447
    {"dump", cmdDump, opts_dump, info_dump},
2448
    {"shutdown", cmdShutdown, opts_shutdown, info_shutdown},
2449 2450 2451
    {"setmem", cmdSetmem, opts_setmem, info_setmem},
    {"setmaxmem", cmdSetmaxmem, opts_setmaxmem, info_setmaxmem},
    {"setvcpus", cmdSetvcpus, opts_setvcpus, info_setvcpus},
K
Karel Zak 已提交
2452
    {"suspend", cmdSuspend, opts_suspend, info_suspend},
2453
    {"undefine", cmdUndefine, opts_undefine, info_undefine},
2454 2455
    {"vcpuinfo", cmdVcpuinfo, opts_vcpuinfo, info_vcpuinfo},
    {"vcpupin", cmdVcpupin, opts_vcpupin, info_vcpupin},
2456
    {"version", cmdVersion, NULL, info_version},
2457
    {"vncdisplay", cmdVNCDisplay, opts_vncdisplay, info_vncdisplay},
2458
    {NULL, NULL, NULL, NULL}
K
Karel Zak 已提交
2459 2460 2461 2462 2463 2464
};

/* ---------------
 * Utils for work with command definition
 * ---------------
 */
K
Karel Zak 已提交
2465
static const char *
2466 2467
vshCmddefGetInfo(vshCmdDef * cmd, const char *name)
{
K
Karel Zak 已提交
2468
    vshCmdInfo *info;
2469

K
Karel Zak 已提交
2470
    for (info = cmd->info; info && info->name; info++) {
2471
        if (strcmp(info->name, name) == 0)
K
Karel Zak 已提交
2472 2473 2474 2475 2476 2477
            return info->data;
    }
    return NULL;
}

static vshCmdOptDef *
2478 2479
vshCmddefGetOption(vshCmdDef * cmd, const char *name)
{
K
Karel Zak 已提交
2480
    vshCmdOptDef *opt;
2481

K
Karel Zak 已提交
2482
    for (opt = cmd->opts; opt && opt->name; opt++)
2483
        if (strcmp(opt->name, name) == 0)
K
Karel Zak 已提交
2484 2485 2486 2487 2488
            return opt;
    return NULL;
}

static vshCmdOptDef *
2489 2490
vshCmddefGetData(vshCmdDef * cmd, int data_ct)
{
K
Karel Zak 已提交
2491 2492
    vshCmdOptDef *opt;

2493
    for (opt = cmd->opts; opt && opt->name; opt++) {
2494 2495
        if (opt->type == VSH_OT_DATA) {
            if (data_ct == 0)
2496 2497 2498 2499 2500
                return opt;
            else
                data_ct--;
        }
    }
K
Karel Zak 已提交
2501 2502 2503
    return NULL;
}

2504 2505 2506
/*
 * Checks for required options
 */
2507 2508
static int
vshCommandCheckOpts(vshControl * ctl, vshCmd * cmd)
2509 2510 2511
{
    vshCmdDef *def = cmd->def;
    vshCmdOptDef *d;
2512
    int err = 0;
2513 2514 2515 2516

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

            while (o && ok == 0) {
2520
                if (o->def == d)
2521
                    ok = 1;
2522 2523 2524
                o = o->next;
            }
            if (!ok) {
2525 2526
                vshError(ctl, FALSE,
                         d->type == VSH_OT_DATA ?
2527
                         _("command '%s' requires <%s> option") :
2528
                         _("command '%s' requires --%s option"),
2529
                         def->name, d->name);
2530 2531
                err = 1;
            }
2532

2533 2534 2535 2536 2537
        }
    }
    return !err;
}

K
Karel Zak 已提交
2538
static vshCmdDef *
2539 2540
vshCmddefSearch(const char *cmdname)
{
K
Karel Zak 已提交
2541
    vshCmdDef *c;
2542

K
Karel Zak 已提交
2543
    for (c = commands; c->name; c++)
2544
        if (strcmp(c->name, cmdname) == 0)
K
Karel Zak 已提交
2545 2546 2547 2548 2549
            return c;
    return NULL;
}

static int
2550 2551
vshCmddefHelp(vshControl * ctl, const char *cmdname, int withprog)
{
K
Karel Zak 已提交
2552
    vshCmdDef *def = vshCmddefSearch(cmdname);
2553

K
Karel Zak 已提交
2554
    if (!def) {
2555
        vshError(ctl, FALSE, _("command '%s' doesn't exist"), cmdname);
2556 2557
        return FALSE;
    } else {
K
Karel Zak 已提交
2558
        vshCmdOptDef *opt;
2559 2560
        const char *desc = _N(vshCmddefGetInfo(def, "desc"));
        const char *help = _N(vshCmddefGetInfo(def, "help"));
K
Karel Zak 已提交
2561
        const char *syntax = vshCmddefGetInfo(def, "syntax");
K
Karel Zak 已提交
2562

2563
        fputs(_("  NAME\n"), stdout);
2564 2565
        fprintf(stdout, "    %s - %s\n", def->name, help);

K
Karel Zak 已提交
2566
        if (syntax) {
2567
            fputs(("\n  SYNOPSIS\n"), stdout);
K
Karel Zak 已提交
2568 2569 2570 2571 2572 2573
            if (!withprog)
                fprintf(stdout, "    %s\n", syntax);
            else
                fprintf(stdout, "    %s %s\n", progname, syntax);
        }
        if (desc) {
2574
            fputs(_("\n  DESCRIPTION\n"), stdout);
K
Karel Zak 已提交
2575 2576 2577
            fprintf(stdout, "    %s\n", desc);
        }
        if (def->opts) {
2578
            fputs(_("\n  OPTIONS\n"), stdout);
2579
            for (opt = def->opts; opt->name; opt++) {
K
Karel Zak 已提交
2580
                char buf[256];
2581 2582

                if (opt->type == VSH_OT_BOOL)
K
Karel Zak 已提交
2583
                    snprintf(buf, sizeof(buf), "--%s", opt->name);
2584
                else if (opt->type == VSH_OT_INT)
2585
                    snprintf(buf, sizeof(buf), _("--%s <number>"), opt->name);
2586
                else if (opt->type == VSH_OT_STRING)
2587
                    snprintf(buf, sizeof(buf), _("--%s <string>"), opt->name);
2588
                else if (opt->type == VSH_OT_DATA)
K
Karel Zak 已提交
2589
                    snprintf(buf, sizeof(buf), "<%s>", opt->name);
2590

K
Karel Zak 已提交
2591
                fprintf(stdout, "    %-15s  %s\n", buf, opt->help);
2592
            }
K
Karel Zak 已提交
2593 2594 2595 2596 2597 2598 2599 2600 2601 2602
        }
        fputc('\n', stdout);
    }
    return TRUE;
}

/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
2603 2604 2605
static void
vshCommandOptFree(vshCmdOpt * arg)
{
K
Karel Zak 已提交
2606 2607
    vshCmdOpt *a = arg;

2608
    while (a) {
K
Karel Zak 已提交
2609
        vshCmdOpt *tmp = a;
2610

K
Karel Zak 已提交
2611 2612 2613 2614 2615 2616 2617 2618 2619
        a = a->next;

        if (tmp->data)
            free(tmp->data);
        free(tmp);
    }
}

static void
2620 2621
vshCommandFree(vshCmd * cmd)
{
K
Karel Zak 已提交
2622 2623
    vshCmd *c = cmd;

2624
    while (c) {
K
Karel Zak 已提交
2625
        vshCmd *tmp = c;
2626

K
Karel Zak 已提交
2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638
        c = c->next;

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

/*
 * Returns option by name
 */
static vshCmdOpt *
2639 2640
vshCommandOpt(vshCmd * cmd, const char *name)
{
K
Karel Zak 已提交
2641
    vshCmdOpt *opt = cmd->opts;
2642 2643 2644

    while (opt) {
        if (opt->def && strcmp(opt->def->name, name) == 0)
K
Karel Zak 已提交
2645 2646 2647 2648 2649 2650 2651 2652 2653 2654
            return opt;
        opt = opt->next;
    }
    return NULL;
}

/*
 * Returns option as INT
 */
static int
2655 2656
vshCommandOptInt(vshCmd * cmd, const char *name, int *found)
{
K
Karel Zak 已提交
2657 2658
    vshCmdOpt *arg = vshCommandOpt(cmd, name);
    int res = 0;
2659

K
Karel Zak 已提交
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670
    if (arg)
        res = atoi(arg->data);
    if (found)
        *found = arg ? TRUE : FALSE;
    return res;
}

/*
 * Returns option as STRING
 */
static char *
2671 2672
vshCommandOptString(vshCmd * cmd, const char *name, int *found)
{
K
Karel Zak 已提交
2673
    vshCmdOpt *arg = vshCommandOpt(cmd, name);
2674

K
Karel Zak 已提交
2675 2676
    if (found)
        *found = arg ? TRUE : FALSE;
2677 2678

    return arg && arg->data && *arg->data ? arg->data : NULL;
K
Karel Zak 已提交
2679 2680 2681 2682 2683 2684
}

/*
 * Returns TRUE/FALSE if the option exists
 */
static int
2685 2686
vshCommandOptBool(vshCmd * cmd, const char *name)
{
K
Karel Zak 已提交
2687 2688 2689
    return vshCommandOpt(cmd, name) ? TRUE : FALSE;
}

2690

K
Karel Zak 已提交
2691
static virDomainPtr
K
Karel Zak 已提交
2692
vshCommandOptDomainBy(vshControl * ctl, vshCmd * cmd, const char *optname,
2693
                      char **name, int flag)
2694
{
K
Karel Zak 已提交
2695 2696 2697
    virDomainPtr dom = NULL;
    char *n, *end = NULL;
    int id;
2698

K
Karel Zak 已提交
2699
    if (!(n = vshCommandOptString(cmd, optname, NULL))) {
2700
        vshError(ctl, FALSE, _("undefined domain name or id"));
2701
        return NULL;
K
Karel Zak 已提交
2702
    }
2703

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

K
Karel Zak 已提交
2707 2708
    if (name)
        *name = n;
2709

K
Karel Zak 已提交
2710
    /* try it by ID */
2711
    if (flag & VSH_BYID) {
K
Karel Zak 已提交
2712 2713 2714 2715 2716 2717
        id = (int) strtol(n, &end, 10);
        if (id >= 0 && end && *end == '\0') {
            vshDebug(ctl, 5, "%s: <%s> seems like domain ID\n",
                     cmd->def->name, optname);
            dom = virDomainLookupByID(ctl->conn, id);
        }
2718
    }
K
Karel Zak 已提交
2719
    /* try it by UUID */
2720
    if (dom==NULL && (flag & VSH_BYUUID) && strlen(n)==VIR_UUID_STRING_BUFLEN-1) {
K
Karel Zak 已提交
2721
        vshDebug(ctl, 5, "%s: <%s> tring as domain UUID\n",
2722
                 cmd->def->name, optname);
K
Karel Zak 已提交
2723
        dom = virDomainLookupByUUIDString(ctl->conn, n);
K
Karel Zak 已提交
2724
    }
K
Karel Zak 已提交
2725
    /* try it by NAME */
2726
    if (dom==NULL && (flag & VSH_BYNAME)) {
K
Karel Zak 已提交
2727
        vshDebug(ctl, 5, "%s: <%s> tring as domain NAME\n",
2728
                 cmd->def->name, optname);
K
Karel Zak 已提交
2729
        dom = virDomainLookupByName(ctl->conn, n);
2730
    }
K
Karel Zak 已提交
2731

2732
    if (!dom)
2733
        vshError(ctl, FALSE, _("failed to get domain '%s'"), n);
2734

K
Karel Zak 已提交
2735 2736 2737
    return dom;
}

2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774
static virNetworkPtr
vshCommandOptNetworkBy(vshControl * ctl, vshCmd * cmd, const char *optname,
		       char **name, int flag)
{
    virNetworkPtr network = NULL;
    char *n;

    if (!(n = vshCommandOptString(cmd, optname, NULL))) {
        vshError(ctl, FALSE, _("undefined network name"));
        return NULL;
    }

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

    if (name)
        *name = n;

    /* try it by UUID */
    if (network==NULL && (flag & VSH_BYUUID) && strlen(n)==VIR_UUID_STRING_BUFLEN-1) {
        vshDebug(ctl, 5, "%s: <%s> tring as network UUID\n",
		 cmd->def->name, optname);
        network = virNetworkLookupByUUIDString(ctl->conn, n);
    }
    /* try it by NAME */
    if (network==NULL && (flag & VSH_BYNAME)) {
        vshDebug(ctl, 5, "%s: <%s> tring as network NAME\n",
                 cmd->def->name, optname);
        network = virNetworkLookupByName(ctl->conn, n);
    }

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

    return network;
}

K
Karel Zak 已提交
2775 2776 2777 2778
/*
 * Executes command(s) and returns return code from last command
 */
static int
2779 2780
vshCommandRun(vshControl * ctl, vshCmd * cmd)
{
K
Karel Zak 已提交
2781
    int ret = TRUE;
2782 2783

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

K
Karel Zak 已提交
2786 2787
        if (ctl->timing)
            GETTIMEOFDAY(&before);
2788

K
Karel Zak 已提交
2789 2790 2791 2792
        ret = cmd->def->handler(ctl, cmd);

        if (ctl->timing)
            GETTIMEOFDAY(&after);
2793 2794

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

        if (ctl->timing)
2798
            vshPrint(ctl, _("\n(Time: %.3f ms)\n\n"),
2799 2800
                     DIFF_MSEC(&after, &before));
        else
K
Karel Zak 已提交
2801
            vshPrintExtra(ctl, "\n");
K
Karel Zak 已提交
2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816
        cmd = cmd->next;
    }
    return ret;
}

/* ---------------
 * Command string parsing
 * ---------------
 */
#define VSH_TK_ERROR    -1
#define VSH_TK_NONE    0
#define VSH_TK_OPTION    1
#define VSH_TK_DATA    2
#define VSH_TK_END    3

2817 2818 2819
static int
vshCommandGetToken(vshControl * ctl, char *str, char **end, char **res)
{
K
Karel Zak 已提交
2820 2821 2822 2823 2824
    int tk = VSH_TK_NONE;
    int quote = FALSE;
    int sz = 0;
    char *p = str;
    char *tkstr = NULL;
2825

K
Karel Zak 已提交
2826
    *end = NULL;
2827 2828

    while (p && *p && isblank((unsigned char) *p))
K
Karel Zak 已提交
2829
        p++;
2830 2831

    if (p == NULL || *p == '\0')
K
Karel Zak 已提交
2832
        return VSH_TK_END;
2833 2834
    if (*p == ';') {
        *end = ++p;             /* = \0 or begi of next command */
K
Karel Zak 已提交
2835 2836
        return VSH_TK_END;
    }
2837
    while (*p) {
K
Karel Zak 已提交
2838
        /* end of token is blank space or ';' */
2839
        if ((quote == FALSE && isblank((unsigned char) *p)) || *p == ';')
K
Karel Zak 已提交
2840
            break;
2841

2842
        /* end of option name could be '=' */
2843 2844
        if (tk == VSH_TK_OPTION && *p == '=') {
            p++;                /* skip '=' */
2845 2846
            break;
        }
2847 2848 2849 2850

        if (tk == VSH_TK_NONE) {
            if (*p == '-' && *(p + 1) == '-' && *(p + 2)
                && isalnum((unsigned char) *(p + 2))) {
K
Karel Zak 已提交
2851
                tk = VSH_TK_OPTION;
2852
                p += 2;
K
Karel Zak 已提交
2853 2854
            } else {
                tk = VSH_TK_DATA;
2855 2856
                if (*p == '"') {
                    quote = TRUE;
K
Karel Zak 已提交
2857 2858 2859 2860 2861
                    p++;
                } else {
                    quote = FALSE;
                }
            }
2862 2863
            tkstr = p;          /* begin of token */
        } else if (quote && *p == '"') {
K
Karel Zak 已提交
2864 2865
            quote = FALSE;
            p++;
2866
            break;              /* end of "..." token */
K
Karel Zak 已提交
2867 2868 2869 2870 2871
        }
        p++;
        sz++;
    }
    if (quote) {
2872
        vshError(ctl, FALSE, _("missing \""));
K
Karel Zak 已提交
2873 2874
        return VSH_TK_ERROR;
    }
2875
    if (tkstr == NULL || *tkstr == '\0' || p == NULL)
K
Karel Zak 已提交
2876
        return VSH_TK_END;
2877
    if (sz == 0)
K
Karel Zak 已提交
2878
        return VSH_TK_END;
2879

2880
    *res = vshMalloc(ctl, sz + 1);
K
Karel Zak 已提交
2881
    memcpy(*res, tkstr, sz);
2882
    *(*res + sz) = '\0';
K
Karel Zak 已提交
2883 2884 2885 2886 2887 2888

    *end = p;
    return tk;
}

static int
2889 2890
vshCommandParse(vshControl * ctl, char *cmdstr)
{
K
Karel Zak 已提交
2891 2892 2893 2894
    char *str;
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
2895

K
Karel Zak 已提交
2896 2897 2898 2899
    if (ctl->cmd) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
2900 2901

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

K
Karel Zak 已提交
2904
    str = cmdstr;
2905
    while (str && *str) {
K
Karel Zak 已提交
2906 2907 2908
        vshCmdOpt *last = NULL;
        vshCmdDef *cmd = NULL;
        int tk = VSH_TK_NONE;
2909
        int data_ct = 0;
2910

K
Karel Zak 已提交
2911
        first = NULL;
2912 2913

        while (tk != VSH_TK_END) {
K
Karel Zak 已提交
2914 2915
            char *end = NULL;
            vshCmdOptDef *opt = NULL;
2916

K
Karel Zak 已提交
2917
            tkdata = NULL;
2918

K
Karel Zak 已提交
2919 2920
            /* get token */
            tk = vshCommandGetToken(ctl, str, &end, &tkdata);
2921

K
Karel Zak 已提交
2922
            str = end;
2923 2924

            if (tk == VSH_TK_END)
K
Karel Zak 已提交
2925
                break;
2926
            if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
2927
                goto syntaxError;
2928 2929

            if (cmd == NULL) {
K
Karel Zak 已提交
2930
                /* first token must be command name */
2931 2932
                if (tk != VSH_TK_DATA) {
                    vshError(ctl, FALSE,
2933
                             _("unexpected token (command name): '%s'"),
2934
                             tkdata);
K
Karel Zak 已提交
2935 2936 2937
                    goto syntaxError;
                }
                if (!(cmd = vshCmddefSearch(tkdata))) {
2938
                    vshError(ctl, FALSE, _("unknown command: '%s'"), tkdata);
2939
                    goto syntaxError;   /* ... or ignore this command only? */
K
Karel Zak 已提交
2940 2941
                }
                free(tkdata);
2942
            } else if (tk == VSH_TK_OPTION) {
K
Karel Zak 已提交
2943 2944
                if (!(opt = vshCmddefGetOption(cmd, tkdata))) {
                    vshError(ctl, FALSE,
2945
                             _("command '%s' doesn't support option --%s"),
2946
                             cmd->name, tkdata);
K
Karel Zak 已提交
2947 2948
                    goto syntaxError;
                }
2949
                free(tkdata);   /* option name */
K
Karel Zak 已提交
2950 2951 2952 2953 2954
                tkdata = NULL;

                if (opt->type != VSH_OT_BOOL) {
                    /* option data */
                    tk = vshCommandGetToken(ctl, str, &end, &tkdata);
2955 2956
                    str = end;
                    if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
2957
                        goto syntaxError;
2958
                    if (tk != VSH_TK_DATA) {
K
Karel Zak 已提交
2959
                        vshError(ctl, FALSE,
2960
                                 _("expected syntax: --%s <%s>"),
2961 2962
                                 opt->name,
                                 opt->type ==
2963
                                 VSH_OT_INT ? _("number") : _("string"));
K
Karel Zak 已提交
2964 2965 2966
                        goto syntaxError;
                    }
                }
2967
            } else if (tk == VSH_TK_DATA) {
2968
                if (!(opt = vshCmddefGetData(cmd, data_ct++))) {
2969
                    vshError(ctl, FALSE, _("unexpected data '%s'"), tkdata);
K
Karel Zak 已提交
2970 2971 2972 2973 2974
                    goto syntaxError;
                }
            }
            if (opt) {
                /* save option */
2975
                vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));
2976

K
Karel Zak 已提交
2977 2978 2979 2980
                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;
2981

K
Karel Zak 已提交
2982 2983 2984 2985 2986
                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;
2987

K
Karel Zak 已提交
2988
                vshDebug(ctl, 4, "%s: %s(%s): %s\n",
2989 2990
                         cmd->name,
                         opt->name,
2991
                         tk == VSH_TK_OPTION ? _("OPTION") : _("DATA"),
2992
                         arg->data);
K
Karel Zak 已提交
2993 2994 2995 2996
            }
            if (!str)
                break;
        }
2997

K
Karel Zak 已提交
2998 2999
        /* commad parsed -- allocate new struct for the command */
        if (cmd) {
3000
            vshCmd *c = vshMalloc(ctl, sizeof(vshCmd));
3001

K
Karel Zak 已提交
3002 3003 3004 3005
            c->opts = first;
            c->def = cmd;
            c->next = NULL;

3006 3007
            if (!vshCommandCheckOpts(ctl, c))
                goto syntaxError;
3008

K
Karel Zak 已提交
3009 3010 3011 3012 3013 3014 3015
            if (!ctl->cmd)
                ctl->cmd = c;
            if (clast)
                clast->next = c;
            clast = c;
        }
    }
3016

K
Karel Zak 已提交
3017 3018
    return TRUE;

3019
 syntaxError:
K
Karel Zak 已提交
3020 3021 3022 3023 3024 3025
    if (ctl->cmd)
        vshCommandFree(ctl->cmd);
    if (first)
        vshCommandOptFree(first);
    if (tkdata)
        free(tkdata);
3026
    return FALSE;
K
Karel Zak 已提交
3027 3028 3029 3030
}


/* ---------------
3031
 * Misc utils
K
Karel Zak 已提交
3032 3033
 * ---------------
 */
K
Karel Zak 已提交
3034
static const char *
3035 3036
vshDomainStateToString(int state)
{
K
Karel Zak 已提交
3037
    switch (state) {
3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051
    case VIR_DOMAIN_RUNNING:
        return gettext_noop("running");
    case VIR_DOMAIN_BLOCKED:
        return gettext_noop("blocked");
    case VIR_DOMAIN_PAUSED:
        return gettext_noop("paused");
    case VIR_DOMAIN_SHUTDOWN:
        return gettext_noop("in shutdown");
    case VIR_DOMAIN_SHUTOFF:
        return gettext_noop("shut off");
    case VIR_DOMAIN_CRASHED:
        return gettext_noop("crashed");
    default:
        return gettext_noop("no state");  /* = dom0 state */
K
Karel Zak 已提交
3052 3053 3054 3055
    }
    return NULL;
}

3056 3057 3058 3059
static const char *
vshDomainVcpuStateToString(int state)
{
    switch (state) {
3060 3061 3062 3063 3064 3065 3066 3067
    case VIR_VCPU_OFFLINE:
        return gettext_noop("offline");
    case VIR_VCPU_BLOCKED:
        return gettext_noop("blocked");
    case VIR_VCPU_RUNNING:
        return gettext_noop("running");
    default:
        return gettext_noop("no state");
3068 3069 3070 3071
    }
    return NULL;
}

K
Karel Zak 已提交
3072
static int
3073 3074
vshConnectionUsability(vshControl * ctl, virConnectPtr conn, int showerror)
{
3075 3076
    /* TODO: use something like virConnectionState() to
     *       check usability of the connection
K
Karel Zak 已提交
3077 3078 3079
     */
    if (!conn) {
        if (showerror)
3080
            vshError(ctl, FALSE, _("no valid connection"));
K
Karel Zak 已提交
3081 3082 3083 3084 3085
        return FALSE;
    }
    return TRUE;
}

K
Karel Zak 已提交
3086 3087
static void
vshDebug(vshControl * ctl, int level, const char *format, ...)
3088
{
K
Karel Zak 已提交
3089 3090 3091 3092 3093 3094 3095 3096
    va_list ap;

    if (level > ctl->debug)
        return;

    va_start(ap, format);
    vfprintf(stdout, format, ap);
    va_end(ap);
K
Karel Zak 已提交
3097 3098 3099
}

static void
K
Karel Zak 已提交
3100
vshPrintExtra(vshControl * ctl, const char *format, ...)
3101
{
K
Karel Zak 已提交
3102
    va_list ap;
3103

K
Karel Zak 已提交
3104
    if (ctl->quiet == TRUE)
K
Karel Zak 已提交
3105
        return;
3106

K
Karel Zak 已提交
3107
    va_start(ap, format);
3108
    vfprintf(stdout, format, ap);
K
Karel Zak 已提交
3109 3110 3111
    va_end(ap);
}

K
Karel Zak 已提交
3112

K
Karel Zak 已提交
3113
static void
3114 3115
vshError(vshControl * ctl, int doexit, const char *format, ...)
{
K
Karel Zak 已提交
3116
    va_list ap;
3117

K
Karel Zak 已提交
3118
    if (doexit)
3119
        fprintf(stderr, _("%s: error: "), progname);
K
Karel Zak 已提交
3120
    else
3121
        fputs(_("error: "), stderr);
3122

K
Karel Zak 已提交
3123 3124 3125 3126 3127
    va_start(ap, format);
    vfprintf(stderr, format, ap);
    va_end(ap);

    fputc('\n', stderr);
3128

K
Karel Zak 已提交
3129
    if (doexit) {
3130 3131
        if (ctl)
            vshDeinit(ctl);
K
Karel Zak 已提交
3132 3133 3134 3135
        exit(EXIT_FAILURE);
    }
}

3136 3137 3138 3139 3140 3141 3142
static void *
_vshMalloc(vshControl * ctl, size_t size, const char *filename, int line)
{
    void *x;

    if ((x = malloc(size)))
        return x;
3143
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %d bytes"),
3144
             filename, line, (int) size);
3145 3146 3147 3148 3149 3150 3151 3152 3153 3154
    return NULL;
}

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

    if ((x = calloc(nmemb, size)))
        return x;
3155
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %d bytes"),
3156
             filename, line, (int) (size*nmemb));
3157 3158 3159 3160 3161 3162 3163 3164 3165 3166
    return NULL;
}

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

    if ((x = strdup(s)))
        return x;
3167 3168
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %lu bytes"),
             filename, line, (unsigned long)strlen(s));
3169 3170 3171
    return NULL;
}

K
Karel Zak 已提交
3172 3173 3174 3175
/*
 * Initialize vistsh
 */
static int
3176 3177
vshInit(vshControl * ctl)
{
K
Karel Zak 已提交
3178 3179 3180 3181
    if (ctl->conn)
        return FALSE;

    ctl->uid = getuid();
3182

3183 3184
    /* set up the library error handler */
    virSetErrorFunc(NULL, virshErrorHandler);
3185

3186 3187 3188 3189 3190 3191
    /* Force a non-root, Xen connection to readonly */
    if ((ctl->name == NULL ||
         !strcasecmp(ctl->name, "xen")) && ctl->uid != 0)
         ctl->readonly = 1;

    if (!ctl->readonly)
K
Karel Zak 已提交
3192
        ctl->conn = virConnectOpen(ctl->name);
K
Karel Zak 已提交
3193
    else
K
Karel Zak 已提交
3194
        ctl->conn = virConnectOpenReadOnly(ctl->name);
3195

K
Karel Zak 已提交
3196
    if (!ctl->conn)
3197
        vshError(ctl, TRUE, _("failed to connect to the hypervisor"));
K
Karel Zak 已提交
3198 3199 3200 3201 3202 3203 3204 3205 3206

    return TRUE;
}

/* -----------------
 * Readline stuff
 * -----------------
 */

3207
/*
K
Karel Zak 已提交
3208 3209
 * Generator function for command completion.  STATE lets us
 * know whether to start from scratch; without any state
3210
 * (i.e. STATE == 0), then we start at the top of the list.
K
Karel Zak 已提交
3211 3212
 */
static char *
3213 3214
vshReadlineCommandGenerator(const char *text, int state)
{
K
Karel Zak 已提交
3215
    static int list_index, len;
K
Karel Zak 已提交
3216
    const char *name;
K
Karel Zak 已提交
3217 3218 3219

    /* If this is a new word to complete, initialize now.  This
     * includes saving the length of TEXT for efficiency, and
3220
     * initializing the index variable to 0.
K
Karel Zak 已提交
3221 3222 3223
     */
    if (!state) {
        list_index = 0;
3224
        len = strlen(text);
K
Karel Zak 已提交
3225 3226 3227
    }

    /* Return the next name which partially matches from the
3228
     * command list.
K
Karel Zak 已提交
3229
     */
K
Karel Zak 已提交
3230
    while ((name = commands[list_index].name)) {
K
Karel Zak 已提交
3231
        list_index++;
3232
        if (strncmp(name, text, len) == 0)
3233
            return vshStrdup(NULL, name);
K
Karel Zak 已提交
3234 3235 3236 3237 3238 3239 3240
    }

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

static char *
3241 3242
vshReadlineOptionsGenerator(const char *text, int state)
{
K
Karel Zak 已提交
3243 3244
    static int list_index, len;
    static vshCmdDef *cmd = NULL;
K
Karel Zak 已提交
3245
    const char *name;
K
Karel Zak 已提交
3246 3247 3248 3249 3250 3251 3252 3253 3254

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

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

3255
        cmdname = vshCalloc(NULL, (p - rl_line_buffer) + 1, 1);
3256
        memcpy(cmdname, rl_line_buffer, p - rl_line_buffer);
K
Karel Zak 已提交
3257 3258 3259

        cmd = vshCmddefSearch(cmdname);
        list_index = 0;
3260
        len = strlen(text);
K
Karel Zak 已提交
3261 3262 3263 3264 3265
        free(cmdname);
    }

    if (!cmd)
        return NULL;
3266

3267 3268 3269
    if (!cmd->opts)
        return NULL;

K
Karel Zak 已提交
3270
    while ((name = cmd->opts[list_index].name)) {
K
Karel Zak 已提交
3271 3272
        vshCmdOptDef *opt = &cmd->opts[list_index];
        char *res;
3273

K
Karel Zak 已提交
3274
        list_index++;
3275

K
Karel Zak 已提交
3276
        if (opt->type == VSH_OT_DATA)
K
Karel Zak 已提交
3277 3278
            /* ignore non --option */
            continue;
3279

K
Karel Zak 已提交
3280
        if (len > 2) {
3281
            if (strncmp(name, text + 2, len - 2))
K
Karel Zak 已提交
3282 3283
                continue;
        }
3284
        res = vshMalloc(NULL, strlen(name) + 3);
3285
        snprintf(res, strlen(name) + 3,  "--%s", name);
K
Karel Zak 已提交
3286 3287 3288 3289 3290 3291 3292 3293
        return res;
    }

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

static char **
3294 3295 3296
vshReadlineCompletion(const char *text, int start,
                      int end ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
3297 3298
    char **matches = (char **) NULL;

3299
    if (start == 0)
K
Karel Zak 已提交
3300
        /* command name generator */
3301
        matches = rl_completion_matches(text, vshReadlineCommandGenerator);
K
Karel Zak 已提交
3302 3303
    else
        /* commands options */
3304
        matches = rl_completion_matches(text, vshReadlineOptionsGenerator);
K
Karel Zak 已提交
3305 3306 3307 3308 3309
    return matches;
}


static void
3310 3311
vshReadlineInit(void)
{
K
Karel Zak 已提交
3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322
    /* 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;
}

/*
 * Deinitliaze virsh
 */
static int
3323 3324
vshDeinit(vshControl * ctl)
{
K
Karel Zak 已提交
3325
    if (ctl->conn) {
3326 3327 3328 3329
        if (virConnectClose(ctl->conn) != 0) {
            ctl->conn = NULL;   /* prevent recursive call from vshError() */
            vshError(ctl, TRUE,
                     "failed to disconnect from the hypervisor");
K
Karel Zak 已提交
3330 3331 3332 3333
        }
    }
    return TRUE;
}
3334

K
Karel Zak 已提交
3335 3336 3337 3338
/*
 * Print usage
 */
static void
3339 3340
vshUsage(vshControl * ctl, const char *cmdname)
{
K
Karel Zak 已提交
3341
    vshCmdDef *cmd;
3342

K
Karel Zak 已提交
3343 3344
    /* global help */
    if (!cmdname) {
3345
        fprintf(stdout, _("\n%s [options] [commands]\n\n"
3346 3347
                          "  options:\n"
                          "    -c | --connect <uri>    hypervisor connection URI\n"
3348
                          "    -r | --readonly         connect readonly\n"
3349 3350 3351 3352 3353 3354
                          "    -d | --debug <num>      debug level [0-5]\n"
                          "    -h | --help             this help\n"
                          "    -q | --quiet            quiet mode\n"
                          "    -t | --timing           print timing information\n"
                          "    -v | --version          program version\n\n"
                          "  commands (non interactive mode):\n"), progname);
3355 3356 3357

        for (cmd = commands; cmd->name; cmd++)
            fprintf(stdout,
3358
                    "    %-15s %s\n", cmd->name, _N(vshCmddefGetInfo(cmd,
3359
                                                                     "help")));
3360 3361

        fprintf(stdout,
3362
                _("\n  (specify --help <command> for details about the command)\n\n"));
K
Karel Zak 已提交
3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373
        return;
    }
    if (!vshCmddefHelp(ctl, cmdname, TRUE))
        exit(EXIT_FAILURE);
}

/*
 * argv[]:  virsh [options] [command]
 *
 */
static int
3374 3375
vshParseArgv(vshControl * ctl, int argc, char **argv)
{
K
Karel Zak 已提交
3376 3377
    char *last = NULL;
    int i, end = 0, help = 0;
3378
    int arg, idx = 0;
K
Karel Zak 已提交
3379
    struct option opt[] = {
3380 3381 3382 3383 3384
        {"debug", 1, 0, 'd'},
        {"help", 0, 0, 'h'},
        {"quiet", 0, 0, 'q'},
        {"timing", 0, 0, 't'},
        {"version", 0, 0, 'v'},
K
Karel Zak 已提交
3385
        {"connect", 1, 0, 'c'},
3386
        {"readonly", 0, 0, 'r'},
K
Karel Zak 已提交
3387
        {0, 0, 0, 0}
3388 3389
    };

K
Karel Zak 已提交
3390 3391

    if (argc < 2)
K
Karel Zak 已提交
3392
        return TRUE;
3393

3394
    /* look for begin of the command, for example:
K
Karel Zak 已提交
3395 3396 3397 3398
     *   ./virsh --debug 5 -q command --cmdoption
     *                  <--- ^ --->
     *        getopt() stuff | command suff
     */
3399
    for (i = 1; i < argc; i++) {
K
Karel Zak 已提交
3400 3401
        if (*argv[i] != '-') {
            int valid = FALSE;
3402

K
Karel Zak 已提交
3403 3404 3405 3406
            /* non "--option" argv, is it command? */
            if (last) {
                struct option *o;
                int sz = strlen(last);
3407 3408

                for (o = opt; o->name; o++) {
3409 3410 3411 3412 3413 3414 3415 3416
                    if (o->has_arg == 1){
                        if (sz == 2 && *(last + 1) == o->val)
                            /* valid virsh short option */
                            valid = TRUE;
                        else if (sz > 2 && strcmp(o->name, last + 2) == 0)
                            /* valid virsh long option */
                            valid = TRUE;
                    }
K
Karel Zak 已提交
3417 3418 3419 3420 3421 3422 3423 3424 3425 3426
                }
            }
            if (!valid) {
                end = i;
                break;
            }
        }
        last = argv[i];
    }
    end = end ? : argc;
3427

K
Karel Zak 已提交
3428
    /* standard (non-command) options */
3429
    while ((arg = getopt_long(end, argv, "d:hqtc:vr", opt, &idx)) != -1) {
3430
        switch (arg) {
3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448
        case 'd':
            ctl->debug = atoi(optarg);
            break;
        case 'h':
            help = 1;
            break;
        case 'q':
            ctl->quiet = TRUE;
            break;
        case 't':
            ctl->timing = TRUE;
            break;
        case 'c':
            ctl->name = vshStrdup(ctl, optarg);
            break;
        case 'v':
            fprintf(stdout, "%s\n", VERSION);
            exit(EXIT_SUCCESS);
3449 3450 3451
        case 'r':
            ctl->readonly = TRUE;
            break;
3452 3453 3454 3455
        default:
            vshError(ctl, TRUE,
                     _("unsupported option '-%c'. See --help."), arg);
            break;
K
Karel Zak 已提交
3456 3457 3458 3459 3460 3461 3462
        }
    }

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

K
Karel Zak 已提交
3465 3466 3467
    if (argc > end) {
        /* parse command */
        char *cmdstr;
3468 3469
        int sz = 0, ret;

K
Karel Zak 已提交
3470 3471
        ctl->imode = FALSE;

3472 3473 3474
        for (i = end; i < argc; i++)
            sz += strlen(argv[i]) + 1;  /* +1 is for blank space between items */

3475
        cmdstr = vshCalloc(ctl, sz + 1, 1);
3476 3477

        for (i = end; i < argc; i++) {
K
Karel Zak 已提交
3478 3479 3480 3481
            strncat(cmdstr, argv[i], sz);
            sz -= strlen(argv[i]);
            strncat(cmdstr, " ", sz--);
        }
K
Karel Zak 已提交
3482
        vshDebug(ctl, 2, "command: \"%s\"\n", cmdstr);
K
Karel Zak 已提交
3483
        ret = vshCommandParse(ctl, cmdstr);
3484

K
Karel Zak 已提交
3485 3486 3487 3488 3489 3490
        free(cmdstr);
        return ret;
    }
    return TRUE;
}

3491 3492 3493 3494
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
3495
    char *defaultConn;
K
Karel Zak 已提交
3496 3497
    int ret = TRUE;

3498 3499
    if (!setlocale(LC_ALL, "")) {
        perror("setlocale");
3500
        return -1;
3501 3502 3503
    }
    if (!bindtextdomain(GETTEXT_PACKAGE, LOCALEBASEDIR)) {
        perror("bindtextdomain");
3504
        return -1;
3505 3506 3507
    }
    if (!textdomain(GETTEXT_PACKAGE)) {
        perror("textdomain");
3508
        return -1;
3509 3510
    }

3511
    if (!(progname = strrchr(argv[0], '/')))
K
Karel Zak 已提交
3512 3513 3514
        progname = argv[0];
    else
        progname++;
3515

K
Karel Zak 已提交
3516
    memset(ctl, 0, sizeof(vshControl));
3517
    ctl->imode = TRUE;          /* default is interactive mode */
K
Karel Zak 已提交
3518

3519
    if ((defaultConn = getenv("VIRSH_DEFAULT_CONNECT_URI"))) {
3520
        ctl->name = strdup(defaultConn);
3521 3522
    }

K
Karel Zak 已提交
3523 3524
    if (!vshParseArgv(ctl, argc, argv))
        exit(EXIT_FAILURE);
3525

K
Karel Zak 已提交
3526 3527
    if (!vshInit(ctl))
        exit(EXIT_FAILURE);
3528

K
Karel Zak 已提交
3529
    if (!ctl->imode) {
3530
        ret = vshCommandRun(ctl, ctl->cmd);
3531
    } else {
K
Karel Zak 已提交
3532 3533
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
3534
            vshPrint(ctl,
3535
                     _("Welcome to %s, the virtualization interactive terminal.\n\n"),
3536
                     progname);
K
Karel Zak 已提交
3537
            vshPrint(ctl,
3538
                     _("Type:  'help' for help with commands\n"
3539
                       "       'quit' to quit\n\n"));
K
Karel Zak 已提交
3540
        }
K
Karel Zak 已提交
3541
        vshReadlineInit();
K
Karel Zak 已提交
3542
        do {
3543 3544 3545 3546
            ctl->cmdstr =
                readline(ctl->uid == 0 ? VSH_PROMPT_RW : VSH_PROMPT_RO);
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
3547 3548 3549 3550 3551 3552 3553
            if (*ctl->cmdstr) {
                add_history(ctl->cmdstr);
                if (vshCommandParse(ctl, ctl->cmdstr))
                    vshCommandRun(ctl, ctl->cmd);
            }
            free(ctl->cmdstr);
            ctl->cmdstr = NULL;
3554
        } while (ctl->imode);
K
Karel Zak 已提交
3555

3556 3557
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
3558
    }
3559

K
Karel Zak 已提交
3560 3561
    vshDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
3562
}
K
Karel Zak 已提交
3563 3564 3565 3566 3567 3568

/*
 * vim: set tabstop=4:
 * vim: set shiftwidth=4:
 * vim: set expandtab:
 */
3569 3570 3571 3572 3573 3574 3575 3576
/*
 * Local variables:
 *  indent-tabs-mode: nil
 *  c-indent-level: 4
 *  c-basic-offset: 4
 *  tab-width: 4
 * End:
 */