xend_internal.c 98.3 KB
Newer Older
1 2 3
/*
 * xend_internal.c: access to Xen though the Xen Daemon interface
 *
4
 * Copyright (C) 2010-2013 Red Hat, Inc.
5
 * Copyright (C) 2005 Anthony Liguori <aliguori@us.ibm.com>
6
 *
E
Eric Blake 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
20 21
 */

22
#include <config.h>
23

24 25 26 27 28
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/errno.h>
R
Richard W.M. Jones 已提交
29 30
#include <sys/stat.h>
#include <fcntl.h>
31 32 33 34 35 36 37 38 39
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <stdarg.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netdb.h>
40
#include <errno.h>
41

42
#include "virerror.h"
43
#include "virlog.h"
44
#include "datatypes.h"
45
#include "xend_internal.h"
46
#include "driver.h"
47
#include "virsexpr.h"
48
#include "xen_sxpr.h"
49
#include "virbuffer.h"
50
#include "viruuid.h"
51 52
#include "xen_driver.h"
#include "xen_hypervisor.h"
53
#include "xs_internal.h" /* To extract VNC port & Serial console TTY */
54
#include "viralloc.h"
55
#include "count-one-bits.h"
E
Eric Blake 已提交
56
#include "virfile.h"
M
Martin Kletzander 已提交
57
#include "viruri.h"
58
#include "device_conf.h"
59
#include "virstring.h"
60

61 62 63
/* required for cpumap_t */
#include <xen/dom0_ops.h>

64 65
#define VIR_FROM_THIS VIR_FROM_XEND

66 67 68
/*
 * The number of Xen scheduler parameters
 */
69

70
#define XEND_RCV_BUF_MAX_LEN (256 * 1024)
D
Daniel Veillard 已提交
71

72
static int
73 74
virDomainXMLDevID(virConnectPtr conn, virDomainDefPtr domain,
                  virDomainDeviceDefPtr dev, char *class,
75
                  char *ref, int ref_len);
76

77 78 79 80 81 82 83 84 85
/**
 * do_connect:
 * @xend: pointer to the Xen Daemon structure
 *
 * Internal routine to (re)connect to the daemon
 *
 * Returns the socket file descriptor or -1 in case of error
 */
static int
86
do_connect(virConnectPtr xend)
87 88
{
    int s;
89
    int no_slow_start = 1;
90
    xenUnifiedPrivatePtr priv = xend->privateData;
91

92
    s = socket(priv->addrfamily, SOCK_STREAM, priv->addrprotocol);
D
Daniel Veillard 已提交
93
    if (s == -1) {
94 95
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("failed to create a socket"));
96
        return -1;
D
Daniel Veillard 已提交
97
    }
98

99
    /*
100
     * try to deactivate slow-start
101
     */
102 103
    ignore_value(setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *)&no_slow_start,
                            sizeof(no_slow_start)));
104

105
    if (connect(s, (struct sockaddr *)&priv->addr, priv->addrlen) == -1) {
106
        VIR_FORCE_CLOSE(s); /* preserves errno */
107 108

        /*
J
John Levon 已提交
109 110
         * Connecting to XenD when privileged is mandatory, so log this
         * error
111
         */
J
John Levon 已提交
112
        if (xenHavePrivilege()) {
113 114
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("failed to connect to xend"));
115
        }
116 117 118 119 120 121 122
    }

    return s;
}

/**
 * wr_sync:
123
 * @xend: the xend connection object
124 125 126 127 128 129 130 131 132 133
 * @fd:  the file descriptor
 * @buffer: the I/O buffer
 * @size: the size of the I/O
 * @do_read: write operation if 0, read operation otherwise
 *
 * Do a synchronous read or write on the file descriptor
 *
 * Returns the number of bytes exchanged, or -1 in case of error
 */
static size_t
134
wr_sync(int fd, void *buffer, size_t size, int do_read)
135 136 137 138 139 140 141
{
    size_t offset = 0;

    while (offset < size) {
        ssize_t len;

        if (do_read) {
142
            len = read(fd, ((char *) buffer) + offset, size - offset);
143
        } else {
144
            len = write(fd, ((char *) buffer) + offset, size - offset);
145 146 147 148 149 150 151 152 153 154 155 156 157 158
        }

        /* recoverable error, retry  */
        if ((len == -1) && ((errno == EAGAIN) || (errno == EINTR))) {
            continue;
        }

        /* eof */
        if (len == 0) {
            break;
        }

        /* unrecoverable error */
        if (len == -1) {
159
            if (do_read)
160 161
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               "%s", _("failed to read from Xen Daemon"));
162
            else
163 164
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               "%s", _("failed to write to Xen Daemon"));
165

166
            return -1;
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
        }

        offset += len;
    }

    return offset;
}

/**
 * sread:
 * @fd:  the file descriptor
 * @buffer: the I/O buffer
 * @size: the size of the I/O
 *
 * Internal routine to do a synchronous read
 *
 * Returns the number of bytes read, or -1 in case of error
 */
static ssize_t
186
sread(int fd, void *buffer, size_t size)
187
{
188
    return wr_sync(fd, buffer, size, 1);
189 190 191 192 193 194 195 196 197 198 199 200 201
}

/**
 * swrite:
 * @fd:  the file descriptor
 * @buffer: the I/O buffer
 * @size: the size of the I/O
 *
 * Internal routine to do a synchronous write
 *
 * Returns the number of bytes written, or -1 in case of error
 */
static ssize_t
202
swrite(int fd, const void *buffer, size_t size)
203
{
204
    return wr_sync(fd, (void *) buffer, size, 0);
205 206 207 208 209 210 211 212 213 214 215 216
}

/**
 * swrites:
 * @fd:  the file descriptor
 * @string: the string to write
 *
 * Internal routine to do a synchronous write of a string
 *
 * Returns the number of bytes written, or -1 in case of error
 */
static ssize_t
217
swrites(int fd, const char *string)
218
{
219
    return swrite(fd, string, strlen(string));
220 221
}

222 223 224 225 226 227 228 229 230 231 232
/**
 * sreads:
 * @fd:  the file descriptor
 * @buffer: the I/O buffer
 * @n_buffer: the size of the I/O buffer
 *
 * Internal routine to do a synchronous read of a line
 *
 * Returns the number of bytes read, or -1 in case of error
 */
static ssize_t
233
sreads(int fd, char *buffer, size_t n_buffer)
234 235 236 237
{
    size_t offset;

    if (n_buffer < 1)
238
        return -1;
239 240 241 242

    for (offset = 0; offset < (n_buffer - 1); offset++) {
        ssize_t ret;

243
        ret = sread(fd, buffer + offset, 1);
244 245 246 247 248 249 250 251 252 253 254 255 256 257
        if (ret == 0)
            break;
        else if (ret == -1)
            return ret;

        if (buffer[offset] == '\n') {
            offset++;
            break;
        }
    }
    buffer[offset] = 0;

    return offset;
}
258 259 260 261

static int
istartswith(const char *haystack, const char *needle)
{
262
    return STRCASEEQLEN(haystack, needle, strlen(needle));
263 264
}

265

266 267 268 269 270 271
/**
 * xend_req:
 * @fd: the file descriptor
 * @content: the buffer to store the content
 *
 * Read the HTTP response from a Xen Daemon request.
272 273
 * If the response contains content, memory is allocated to
 * hold the content.
274
 *
275 276
 * Returns the HTTP return code and @content is set to the
 * allocated memory containing HTTP content.
277
 */
278
static int ATTRIBUTE_NONNULL(2)
279
xend_req(int fd, char **content)
280
{
281 282
    char *buffer;
    size_t buffer_size = 4096;
283
    int content_length = 0;
284 285
    int retcode = 0;

286 287 288 289 290 291
    if (VIR_ALLOC_N(buffer, buffer_size) < 0) {
        virReportOOMError();
        return -1;
    }

    while (sreads(fd, buffer, buffer_size) > 0) {
292
        if (STREQ(buffer, "\r\n"))
293
            break;
294 295 296 297 298

        if (istartswith(buffer, "Content-Length: "))
            content_length = atoi(buffer + 16);
        else if (istartswith(buffer, "HTTP/1.1 "))
            retcode = atoi(buffer + 9);
299 300
    }

301 302
    VIR_FREE(buffer);

303
    if (content_length > 0) {
304 305
        ssize_t ret;

J
Jim Fehlig 已提交
306
        if (content_length > XEND_RCV_BUF_MAX_LEN) {
307 308 309 310 311
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Xend returned HTTP Content-Length of %d, "
                             "which exceeds maximum of %d"),
                           content_length,
                           XEND_RCV_BUF_MAX_LEN);
J
Jim Fehlig 已提交
312 313 314 315 316 317
            return -1;
        }

        /* Allocate one byte beyond the end of the largest buffer we will read.
           Combined with the fact that VIR_ALLOC_N zeros the returned buffer,
           this guarantees that "content" will always be NUL-terminated. */
318
        if (VIR_ALLOC_N(*content, content_length + 1) < 0) {
319 320 321
            virReportOOMError();
            return -1;
        }
322

323
        ret = sread(fd, *content, content_length);
324 325
        if (ret < 0)
            return -1;
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    }

    return retcode;
}

/**
 * xend_get:
 * @xend: pointer to the Xen Daemon structure
 * @path: the path used for the HTTP request
 * @content: the buffer to store the content
 *
 * Do an HTTP GET RPC with the Xen Daemon
 *
 * Returns the HTTP return code or -1 in case or error.
 */
J
Jim Fehlig 已提交
341
static int ATTRIBUTE_NONNULL(3)
342
xend_get(virConnectPtr xend, const char *path, char **content)
343 344 345 346 347 348 349
{
    int ret;
    int s = do_connect(xend);

    if (s == -1)
        return s;

350 351 352
    swrites(s, "GET ");
    swrites(s, path);
    swrites(s, " HTTP/1.1\r\n");
353

354
    swrites(s,
355 356 357 358
            "Host: localhost:8000\r\n"
            "Accept-Encoding: identity\r\n"
            "Content-Type: application/x-www-form-urlencoded\r\n" "\r\n");

359
    ret = xend_req(s, content);
360
    VIR_FORCE_CLOSE(s);
361

362 363 364 365
    if (ret < 0)
        return ret;

    if ((ret >= 300) && ((ret != 404) || (!STRPREFIX(path, "/xend/domain/")))) {
366 367 368
        virReportError(VIR_ERR_GET_FAILED,
                       _("%d status from xen daemon: %s:%s"),
                       ret, path, NULLSTR(*content));
D
Daniel Veillard 已提交
369 370
    }

371 372 373 374 375 376 377
    return ret;
}

/**
 * xend_post:
 * @xend: pointer to the Xen Daemon structure
 * @path: the path used for the HTTP request
378
 * @ops: the information sent for the POST
379 380 381 382 383 384 385
 *
 * Do an HTTP POST RPC with the Xen Daemon, this usually makes changes at the
 * Xen level.
 *
 * Returns the HTTP return code or -1 in case or error.
 */
static int
386
xend_post(virConnectPtr xend, const char *path, const char *ops)
387 388
{
    char buffer[100];
389
    char *err_buf = NULL;
390 391 392 393 394 395
    int ret;
    int s = do_connect(xend);

    if (s == -1)
        return s;

396 397 398
    swrites(s, "POST ");
    swrites(s, path);
    swrites(s, " HTTP/1.1\r\n");
399

400
    swrites(s,
401 402 403 404
            "Host: localhost:8000\r\n"
            "Accept-Encoding: identity\r\n"
            "Content-Type: application/x-www-form-urlencoded\r\n"
            "Content-Length: ");
405
    snprintf(buffer, sizeof(buffer), "%d", (int) strlen(ops));
406 407 408
    swrites(s, buffer);
    swrites(s, "\r\n\r\n");
    swrites(s, ops);
409

410
    ret = xend_req(s, &err_buf);
411
    VIR_FORCE_CLOSE(s);
412

D
Daniel Veillard 已提交
413
    if ((ret < 0) || (ret >= 300)) {
414 415
        virReportError(VIR_ERR_POST_FAILED,
                       _("xend_post: error from xen daemon: %s"), err_buf);
416
    } else if ((ret == 202) && err_buf && (strstr(err_buf, "failed") != NULL)) {
417 418
        virReportError(VIR_ERR_POST_FAILED,
                       _("xend_post: error from xen daemon: %s"), err_buf);
419
        ret = -1;
420 421
    } else if (((ret >= 200) && (ret <= 202)) && err_buf &&
               (strstr(err_buf, "xend.err") != NULL)) {
422 423 424
        /* This is to catch case of things like 'virsh dump Domain-0 foo'
         * which returns a success code, but the word 'xend.err'
         * in body to indicate error :-(
425
         */
426 427
        virReportError(VIR_ERR_POST_FAILED,
                       _("xend_post: error from xen daemon: %s"), err_buf);
428
        ret = -1;
D
Daniel Veillard 已提交
429 430
    }

431
    VIR_FREE(err_buf);
432 433
    return ret;
}
434

435 436 437 438 439 440 441 442 443 444

/**
 * http2unix:
 * @ret: the http return code
 *
 * Convert the HTTP return code to 0/-1 and set errno if needed
 *
 * Return -1 in case of error code 0 otherwise
 */
static int
445
http2unix(int ret)
446 447 448 449 450 451 452 453 454 455 456
{
    switch (ret) {
        case -1:
            break;
        case 200:
        case 201:
        case 202:
            return 0;
        case 404:
            errno = ESRCH;
            break;
457 458 459
        case 500:
            errno = EIO;
            break;
460
        default:
461 462
            virReportError(VIR_ERR_HTTP_ERROR,
                           _("Unexpected HTTP error code %d"), ret);
463 464 465 466 467 468 469
            errno = EINVAL;
            break;
    }
    return -1;
}

/**
470
 * xend_op_ext:
471 472 473 474 475 476 477 478 479 480
 * @xend: pointer to the Xen Daemon structure
 * @path: path for the object
 * @key: the key for the operation
 * @ap: input values to pass to the operation
 *
 * internal routine to run a POST RPC operation to the Xen Daemon
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
static int
481
xend_op_ext(virConnectPtr xend, const char *path, const char *key, va_list ap)
482 483
{
    const char *k = key, *v;
484
    virBuffer buf = VIR_BUFFER_INITIALIZER;
485
    int ret;
486
    char *content;
487 488 489 490

    while (k) {
        v = va_arg(ap, const char *);

P
Philipp Hahn 已提交
491 492 493
        virBufferURIEncodeString(&buf, k);
        virBufferAddChar(&buf, '=');
        virBufferURIEncodeString(&buf, v);
494 495 496
        k = va_arg(ap, const char *);

        if (k)
497
            virBufferAddChar(&buf, '&');
498 499
    }

500
    if (virBufferError(&buf)) {
501
        virBufferFreeAndReset(&buf);
502
        virReportOOMError();
503 504 505 506
        return -1;
    }

    content = virBufferContentAndReset(&buf);
507
    VIR_DEBUG("xend op: %s\n", content);
508
    ret = http2unix(xend_post(xend, path, content));
509
    VIR_FREE(content);
510 511

    return ret;
512 513
}

514

515
/**
516
 * xend_op:
517 518 519 520 521 522 523 524 525 526 527
 * @xend: pointer to the Xen Daemon structure
 * @name: the domain name target of this operation
 * @key: the key for the operation
 * @ap: input values to pass to the operation
 * @...: input values to pass to the operation
 *
 * internal routine to run a POST RPC operation to the Xen Daemon targetting
 * a given domain.
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
P
Paolo Bonzini 已提交
528
static int ATTRIBUTE_SENTINEL
529
xend_op(virConnectPtr xend, const char *name, const char *key, ...)
530 531 532 533 534 535 536 537
{
    char buffer[1024];
    va_list ap;
    int ret;

    snprintf(buffer, sizeof(buffer), "/xend/domain/%s", name);

    va_start(ap, key);
538
    ret = xend_op_ext(xend, buffer, key, ap);
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
    va_end(ap);

    return ret;
}


/**
 * sexpr_get:
 * @xend: pointer to the Xen Daemon structure
 * @fmt: format string for the path of the operation
 * @...: extra data to build the path of the operation
 *
 * Internal routine to run a simple GET RPC operation to the Xen Daemon
 *
 * Returns a parsed S-Expression in case of success, NULL in case of failure
 */
555
static struct sexpr *sexpr_get(virConnectPtr xend, const char *fmt, ...)
556
  ATTRIBUTE_FMT_PRINTF(2,3);
557

558
static struct sexpr *
559
sexpr_get(virConnectPtr xend, const char *fmt, ...)
560
{
561
    char *buffer = NULL;
562 563 564
    char path[1024];
    va_list ap;
    int ret;
565
    struct sexpr *res = NULL;
566 567 568 569 570

    va_start(ap, fmt);
    vsnprintf(path, sizeof(path), fmt, ap);
    va_end(ap);

571
    ret = xend_get(xend, path, &buffer);
572
    ret = http2unix(ret);
573
    if (ret == -1)
574 575 576 577 578 579
        goto cleanup;

    if (buffer == NULL)
        goto cleanup;

    res = string2sexpr(buffer);
580

581 582 583
cleanup:
    VIR_FREE(buffer);
    return res;
584 585 586 587 588 589 590 591 592 593
}

/**
 * sexpr_uuid:
 * @ptr: where to store the UUID, incremented
 * @sexpr: an S-Expression
 * @name: the name for the value
 *
 * convenience function to lookup an UUID value from the S-Expression
 *
594
 * Returns a -1 on error, 0 on success
595
 */
596
static int
597
sexpr_uuid(unsigned char *ptr, const struct sexpr *node, const char *path)
598 599
{
    const char *r = sexpr_node(node, path);
600 601 602
    if (!r)
        return -1;
    return virUUIDParse(r, ptr);
603 604 605 606 607
}

/* PUBLIC FUNCTIONS */

/**
608
 * xenDaemonOpen_unix:
609
 * @conn: an existing virtual connection block
610 611 612 613 614
 * @path: the path for the Xen Daemon socket
 *
 * Creates a localhost Xen Daemon connection
 * Note: this doesn't try to check if the connection actually works
 *
615
 * Returns 0 in case of success, -1 in case of error.
616
 */
617
int
618
xenDaemonOpen_unix(virConnectPtr conn, const char *path)
619 620
{
    struct sockaddr_un *addr;
621
    xenUnifiedPrivatePtr priv = conn->privateData;
622

623 624
    memset(&priv->addr, 0, sizeof(priv->addr));
    priv->addrfamily = AF_UNIX;
625 626 627 628 629
    /*
     * This must be zero on Solaris at least for AF_UNIX (which should
     * really be PF_UNIX, but doesn't matter).
     */
    priv->addrprotocol = 0;
630 631 632
    priv->addrlen = sizeof(struct sockaddr_un);

    addr = (struct sockaddr_un *)&priv->addr;
633 634
    addr->sun_family = AF_UNIX;
    memset(addr->sun_path, 0, sizeof(addr->sun_path));
C
Chris Lalancette 已提交
635 636
    if (virStrcpyStatic(addr->sun_path, path) == NULL)
        return -1;
637

638
    return 0;
639 640
}

641

642
/**
643
 * xenDaemonOpen_tcp:
644
 * @conn: an existing virtual connection block
645
 * @host: the host name for the Xen Daemon
646
 * @port: the port
647 648 649 650
 *
 * Creates a possibly remote Xen Daemon connection
 * Note: this doesn't try to check if the connection actually works
 *
651
 * Returns 0 in case of success, -1 in case of error.
652
 */
653
static int
654
xenDaemonOpen_tcp(virConnectPtr conn, const char *host, const char *port)
655
{
656
    xenUnifiedPrivatePtr priv = conn->privateData;
657 658 659 660
    struct addrinfo *res, *r;
    struct addrinfo hints;
    int saved_errno = EINVAL;
    int ret;
661

662 663 664
    priv->addrlen = 0;
    memset(&priv->addr, 0, sizeof(priv->addr));

665
    /* http://people.redhat.com/drepper/userapi-ipv6.html */
666
    memset (&hints, 0, sizeof(hints));
667 668 669 670 671
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_ADDRCONFIG;

    ret = getaddrinfo (host, port, &hints, &res);
    if (ret != 0) {
672 673 674
        virReportError(VIR_ERR_UNKNOWN_HOST,
                       _("unable to resolve hostname '%s': %s"),
                       host, gai_strerror (ret));
675 676 677 678 679 680 681
        return -1;
    }

    /* Try to connect to each returned address in turn. */
    for (r = res; r; r = r->ai_next) {
        int sock;

682
        sock = socket(r->ai_family, SOCK_STREAM, r->ai_protocol);
683 684 685
        if (sock == -1) {
            saved_errno = errno;
            continue;
686
        }
687

688
        if (connect(sock, r->ai_addr, r->ai_addrlen) == -1) {
689
            saved_errno = errno;
690
            VIR_FORCE_CLOSE(sock);
691 692 693 694 695 696 697 698 699
            continue;
        }

        priv->addrlen = r->ai_addrlen;
        priv->addrfamily = r->ai_family;
        priv->addrprotocol = r->ai_protocol;
        memcpy(&priv->addr,
               r->ai_addr,
               r->ai_addrlen);
700
        VIR_FORCE_CLOSE(sock);
701
        break;
702 703
    }

704
    freeaddrinfo(res);
705

706
    if (!priv->addrlen) {
707 708
        /* Don't raise error when unprivileged, since proxy takes over */
        if (xenHavePrivilege())
709
            virReportSystemError(saved_errno,
710 711
                                 _("unable to connect to '%s:%s'"),
                                 host, port);
712 713
        return -1;
    }
714

715
    return 0;
716 717
}

718

719 720
/**
 * xend_wait_for_devices:
P
Philipp Hahn 已提交
721
 * @xend: pointer to the Xen Daemon block
722 723 724 725 726 727 728 729
 * @name: name for the domain
 *
 * Block the domain until all the virtual devices are ready. This operation
 * is needed when creating a domain before resuming it.
 *
 * Returns 0 in case of success, -1 (with errno) in case of error.
 */
int
730
xend_wait_for_devices(virConnectPtr xend, const char *name)
731 732 733 734
{
    return xend_op(xend, name, "op", "wait_for_devices", NULL);
}

735

736
/**
737
 * xenDaemonListDomainsOld:
P
Philipp Hahn 已提交
738
 * @xend: pointer to the Xen Daemon block
739 740 741 742 743 744
 *
 * This method will return an array of names of currently running
 * domains.  The memory should be released will a call to free().
 *
 * Returns a list of names or NULL in case of error.
 */
745
char **
746
xenDaemonListDomainsOld(virConnectPtr xend)
747 748 749 750 751 752 753 754 755 756 757
{
    struct sexpr *root = NULL;
    char **ret = NULL;
    int count = 0;
    int i;
    struct sexpr *_for_i, *node;

    root = sexpr_get(xend, "/xend/domain");
    if (root == NULL)
        goto error;

758 759
    for (_for_i = root, node = root->u.s.car; _for_i->kind == SEXPR_CONS;
         _for_i = _for_i->u.s.cdr, node = _for_i->u.s.car) {
760 761 762 763 764
        if (node->kind != SEXPR_VALUE)
            continue;
        count++;
    }

E
Eric Blake 已提交
765 766
    if (VIR_ALLOC_N(ret, count + 1) < 0) {
        virReportOOMError();
767
        goto error;
E
Eric Blake 已提交
768
    }
769 770

    i = 0;
771 772
    for (_for_i = root, node = root->u.s.car; _for_i->kind == SEXPR_CONS;
         _for_i = _for_i->u.s.cdr, node = _for_i->u.s.car) {
773 774
        if (node->kind != SEXPR_VALUE)
            continue;
E
Eric Blake 已提交
775 776 777
        ret[i] = strdup(node->u.value);
        if (!ret[i])
            goto no_memory;
778 779 780 781 782 783 784 785
        i++;
    }

    ret[i] = NULL;

  error:
    sexpr_free(root);
    return ret;
E
Eric Blake 已提交
786 787 788 789 790 791

no_memory:
    for (i = 0; i < count; i++)
        VIR_FREE(ret[i]);
    VIR_FREE(ret);
    goto error;
792 793
}

794

795
/**
796
 * xenDaemonDomainCreateXML:
797 798 799
 * @xend: A xend instance
 * @sexpr: An S-Expr description of the domain.
 *
P
Philipp Hahn 已提交
800
 * This method will create a domain based on the passed in description.  The
801
 * domain will be paused after creation and must be unpaused with
802
 * xenDaemonResumeDomain() to begin execution.
803 804 805 806 807 808 809
 * This method may be deprecated once switching to XML-RPC based communcations
 * with xend.
 *
 * Returns 0 for success, -1 (with errno) on error
 */

int
810
xenDaemonDomainCreateXML(virConnectPtr xend, const char *sexpr)
811
{
P
Philipp Hahn 已提交
812
    int ret;
813

P
Philipp Hahn 已提交
814
    ret = xend_op(xend, "", "op", "create", "config", sexpr, NULL);
815 816 817

    return ret;
}
818

819

820
/**
821
 * xenDaemonDomainLookupByName_ids:
822
 * @xend: A xend instance
823 824
 * @domname: The name of the domain
 * @uuid: return value for the UUID if not NULL
825 826 827 828 829 830
 *
 * This method looks up the id of a domain
 *
 * Returns the id on success; -1 (with errno) on error
 */
int
831 832
xenDaemonDomainLookupByName_ids(virConnectPtr xend,
                                const char *domname,
833
                                unsigned char *uuid)
834 835 836 837 838
{
    struct sexpr *root;
    const char *value;
    int ret = -1;

839
    if (uuid != NULL)
840
        memset(uuid, 0, VIR_UUID_BUFLEN);
841 842 843 844 845
    root = sexpr_get(xend, "/xend/domain/%s?detail=1", domname);
    if (root == NULL)
        goto error;

    value = sexpr_node(root, "domain/domid");
846
    if (value == NULL) {
847 848
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("domain information incomplete, missing domid"));
849
        goto error;
850
    }
851
    ret = strtol(value, NULL, 0);
852
    if ((ret == 0) && (value[0] != '0')) {
853 854
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("domain information incorrect domid not numeric"));
855
        ret = -1;
856
    } else if (uuid != NULL) {
857
        if (sexpr_uuid(uuid, root, "domain/uuid") < 0) {
858 859
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("domain information incomplete, missing uuid"));
860
        }
861
    }
862

863
  error:
864
    sexpr_free(root);
865
    return ret;
866 867
}

868

869
static int
870 871
xend_detect_config_version(virConnectPtr conn)
{
872 873
    struct sexpr *root;
    const char *value;
874
    xenUnifiedPrivatePtr priv = conn->privateData;
875

876 877
    root = sexpr_get(conn, "/xend/node/");
    if (root == NULL)
878
        return -1;
879

880
    value = sexpr_node(root, "node/xend_config_format");
881

882
    if (value) {
883
        priv->xendConfigVersion = strtol(value, NULL, 10);
884 885 886
    }  else {
        /* Xen prior to 3.0.3 did not have the xend_config_format
           field, and is implicitly version 1. */
887
        priv->xendConfigVersion = XEND_CONFIG_VERSION_3_0_2;
888
    }
889
    sexpr_free(root);
890
    return 0;
891 892
}

D
Daniel Veillard 已提交
893

894 895 896 897 898 899 900 901 902 903
/**
 * sexpr_to_xend_domain_state:
 * @root: an S-Expression describing a domain
 *
 * Internal routine getting the domain's state from the domain root provided.
 *
 * Returns domain's state.
 */
static int
ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2)
904
sexpr_to_xend_domain_state(virDomainDefPtr def, const struct sexpr *root)
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
{
    const char *flags;
    int state = VIR_DOMAIN_NOSTATE;

    if ((flags = sexpr_node(root, "domain/state"))) {
        if (strchr(flags, 'c'))
            state = VIR_DOMAIN_CRASHED;
        else if (strchr(flags, 's'))
            state = VIR_DOMAIN_SHUTOFF;
        else if (strchr(flags, 'd'))
            state = VIR_DOMAIN_SHUTDOWN;
        else if (strchr(flags, 'p'))
            state = VIR_DOMAIN_PAUSED;
        else if (strchr(flags, 'b'))
            state = VIR_DOMAIN_BLOCKED;
        else if (strchr(flags, 'r'))
            state = VIR_DOMAIN_RUNNING;
922
    } else if (def->id < 0 || sexpr_int(root, "domain/status") == 0) {
923 924 925 926 927 928 929
        /* As far as I can see the domain->id is a bad sign for checking
         * inactive domains as this is inaccurate after the domain has
         * been running once. However domain/status from xend seems to
         * be always present and 0 for inactive domains.
         * (keeping the check for id < 0 to be extra safe about backward
         * compatibility)
         */
930 931 932 933 934 935
        state = VIR_DOMAIN_SHUTOFF;
    }

    return state;
}

D
Daniel Veillard 已提交
936
/**
937 938 939 940 941 942 943 944 945 946
 * sexpr_to_xend_domain_info:
 * @root: an S-Expression describing a domain
 * @info: a info data structure to fill=up
 *
 * Internal routine filling up the info structure with the values from
 * the domain root provided.
 *
 * Returns 0 in case of success, -1 in case of error
 */
static int
947
sexpr_to_xend_domain_info(virDomainDefPtr def,
948
                          const struct sexpr *root,
949
                          virDomainInfoPtr info)
950
{
951
    int vcpus;
952

953
    info->state = sexpr_to_xend_domain_state(def, root);
954 955 956
    info->memory = sexpr_u64(root, "domain/memory") << 10;
    info->maxMem = sexpr_u64(root, "domain/maxmem") << 10;
    info->cpuTime = sexpr_float(root, "domain/cpu_time") * 1000000000;
957

958
    vcpus = sexpr_int(root, "domain/vcpus");
959
    info->nrVirtCpu = count_one_bits_l(sexpr_u64(root, "domain/vcpu_avail"));
960 961 962
    if (!info->nrVirtCpu || vcpus < info->nrVirtCpu)
        info->nrVirtCpu = vcpus;

963
    return 0;
964 965
}

966 967 968 969 970 971 972 973 974 975 976
/**
 * sexpr_to_xend_node_info:
 * @root: an S-Expression describing a domain
 * @info: a info data structure to fill up
 *
 * Internal routine filling up the info structure with the values from
 * the node root provided.
 *
 * Returns 0 in case of success, -1 in case of error
 */
static int
977
sexpr_to_xend_node_info(const struct sexpr *root, virNodeInfoPtr info)
978 979 980 981
{
    const char *machine;

    machine = sexpr_node(root, "node/machine");
982
    if (machine == NULL) {
983
        info->model[0] = 0;
984
    } else {
985
        snprintf(&info->model[0], sizeof(info->model) - 1, "%s", machine);
986
        info->model[sizeof(info->model) - 1] = 0;
987 988 989 990 991 992 993
    }
    info->memory = (unsigned long) sexpr_u64(root, "node/total_memory") << 10;

    info->cpus = sexpr_int(root, "node/nr_cpus");
    info->mhz = sexpr_int(root, "node/cpu_mhz");
    info->nodes = sexpr_int(root, "node/nr_nodes");
    info->sockets = sexpr_int(root, "node/sockets_per_node");
994 995 996
    info->cores = sexpr_int(root, "node/cores_per_socket");
    info->threads = sexpr_int(root, "node/threads_per_core");

997 998 999 1000 1001 1002 1003
    /* Xen 3.2.0 replaces sockets_per_node with 'nr_cpus'.
     * Old Xen calculated sockets_per_node using its internal
     * nr_cpus / (nodes*cores*threads), so fake it ourselves
     * in the same way
     */
    if (info->sockets == 0) {
        int nr_cpus = sexpr_int(root, "node/nr_cpus");
1004 1005
        int procs = info->nodes * info->cores * info->threads;
        if (procs == 0) /* Sanity check in case of Xen bugs in futures..*/
1006
            return -1;
1007
        info->sockets = nr_cpus / procs;
1008
    }
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022

    /* On systems where NUMA nodes are not composed of whole sockets either Xen
     * provided us wrong number of sockets per node or we computed the wrong
     * number in the compatibility code above. In such case, we compute the
     * correct number of sockets on the host, lie about the number of NUMA
     * nodes, and force apps to check capabilities XML for the actual NUMA
     * topology.
     */
    if (info->nodes * info->sockets * info->cores * info->threads
        != info->cpus) {
        info->nodes = 1;
        info->sockets = info->cpus / (info->cores * info->threads);
    }

1023
    return 0;
1024 1025
}

1026

1027
/**
1028
 * sexpr_to_xend_topology
1029
 * @root: an S-Expression describing a node
1030
 * @caps: capability info
1031
 *
1032 1033
 * Internal routine populating capability info with
 * NUMA node mapping details
1034
 *
1035 1036
 * Does nothing when the system doesn't support NUMA (not an error).
 *
1037 1038
 * Returns 0 in case of success, -1 in case of error
 */
1039
static int
1040
sexpr_to_xend_topology(const struct sexpr *root, virCapsPtr caps)
1041 1042
{
    const char *nodeToCpu;
1043
    const char *cur;
1044
    virCapsHostNUMACellCPUPtr cpuInfo = NULL;
1045
    int cell, cpu, nb_cpus = 0;
1046
    int n = 0;
1047
    int numCpus;
1048 1049

    nodeToCpu = sexpr_node(root, "node/node_to_cpu");
1050 1051
    if (nodeToCpu == NULL)
        return 0;               /* no NUMA support */
1052 1053 1054

    numCpus = sexpr_int(root, "node/nr_cpus");

1055 1056 1057

    cur = nodeToCpu;
    while (*cur != 0) {
1058
        virBitmapPtr cpuset = NULL;
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
        /*
         * Find the next NUMA cell described in the xend output
         */
        cur = strstr(cur, "node");
        if (cur == NULL)
            break;
        cur += 4;
        cell = virParseNumber(&cur);
        if (cell < 0)
            goto parse_error;
E
Eric Blake 已提交
1069
        virSkipSpacesAndBackslash(&cur);
1070 1071 1072
        if (*cur != ':')
            goto parse_error;
        cur++;
E
Eric Blake 已提交
1073
        virSkipSpacesAndBackslash(&cur);
1074
        if (STRPREFIX(cur, "no cpus")) {
1075
            nb_cpus = 0;
1076 1077
            if (!(cpuset = virBitmapNew(numCpus)))
                goto memory_error;
1078
        } else {
1079
            nb_cpus = virBitmapParse(cur, 'n', &cpuset, numCpus);
1080 1081 1082 1083
            if (nb_cpus < 0)
                goto error;
        }

1084 1085
        if (VIR_ALLOC_N(cpuInfo, numCpus) < 0) {
            virBitmapFree(cpuset);
1086
            goto memory_error;
1087
        }
1088

1089 1090 1091 1092 1093
        for (n = 0, cpu = 0; cpu < numCpus; cpu++) {
            bool used;

            ignore_value(virBitmapGetBit(cpuset, cpu, &used));
            if (used)
1094
                cpuInfo[n++].id = cpu;
1095
        }
1096
        virBitmapFree(cpuset);
1097

1098
        if (virCapabilitiesAddHostNUMACell(caps, cell, nb_cpus, 0, cpuInfo) < 0)
1099
            goto memory_error;
1100
        cpuInfo = NULL;
1101
    }
1102

1103
    return 0;
1104

1105
  parse_error:
1106
    virReportError(VIR_ERR_XEN_CALL, "%s", _("topology syntax error"));
1107
  error:
1108 1109
    virCapabilitiesClearHostNUMACellCPUTopology(cpuInfo, nb_cpus);
    VIR_FREE(cpuInfo);
1110
    return -1;
1111

1112
  memory_error:
1113
    virReportOOMError();
1114
    goto error;
1115 1116
}

1117

1118 1119 1120 1121 1122 1123 1124
/**
 * sexpr_to_domain:
 * @conn: an existing virtual connection block
 * @root: an S-Expression describing a domain
 *
 * Internal routine returning the associated virDomainPtr for this domain
 *
1125
 * Returns the domain def pointer or NULL in case of error.
1126
 */
1127
static virDomainDefPtr
1128
sexpr_to_domain(virConnectPtr conn, const struct sexpr *root)
1129
{
1130
    virDomainDefPtr ret = NULL;
1131
    unsigned char uuid[VIR_UUID_BUFLEN];
1132
    const char *name;
1133
    const char *tmp;
1134
    int id = -1;
1135
    xenUnifiedPrivatePtr priv = conn->privateData;
1136

1137
    if (sexpr_uuid(uuid, root, "domain/uuid") < 0)
1138 1139 1140 1141 1142
        goto error;
    name = sexpr_node(root, "domain/name");
    if (name == NULL)
        goto error;

1143 1144 1145 1146
    tmp = sexpr_node(root, "domain/domid");
    /* New 3.0.4 XenD will not report a domid for inactive domains,
     * so only error out for old XenD
     */
1147
    if (!tmp && priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4)
1148 1149
        goto error;

1150
    if (tmp)
1151
        id = sexpr_int(root, "domain/domid");
1152

1153
    return virDomainDefNew(name, uuid, id);
1154

1155
error:
1156 1157
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("failed to parse Xend domain information"));
1158
    virObjectUnref(ret);
1159
    return NULL;
1160
}
1161

1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183

/*****************************************************************
 ******
 ******
 ******
 ******
             Refactored
 ******
 ******
 ******
 ******
 *****************************************************************/
/**
 * xenDaemonOpen:
 * @conn: an existing virtual connection block
 * @name: optional argument to select a connection type
 * @flags: combination of virDrvOpenFlag(s)
 *
 * Creates a localhost Xen Daemon connection
 *
 * Returns 0 in case of success, -1 in case of error.
 */
1184
int
1185 1186
xenDaemonOpen(virConnectPtr conn,
              virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
1187
              unsigned int flags)
1188
{
1189
    char *port = NULL;
1190
    int ret = -1;
1191

1192
    virCheckFlags(VIR_CONNECT_RO, -1);
E
Eric Blake 已提交
1193

1194 1195
    /* Switch on the scheme, which we expect to be NULL (file),
     * "http" or "xen".
1196
     */
1197
    if (conn->uri->scheme == NULL) {
1198
        /* It should be a file access */
1199
        if (conn->uri->path == NULL) {
1200
            virReportError(VIR_ERR_NO_CONNECT, __FUNCTION__);
1201 1202
            goto failed;
        }
1203 1204
        if (xenDaemonOpen_unix(conn, conn->uri->path) < 0 ||
            xend_detect_config_version(conn) == -1)
1205 1206
            goto failed;
    }
1207
    else if (STRCASEEQ(conn->uri->scheme, "xen")) {
1208
        /*
1209 1210
         * try first to open the unix socket
         */
1211 1212
        if (xenDaemonOpen_unix(conn, "/var/lib/xend/xend-socket") == 0 &&
            xend_detect_config_version(conn) != -1)
1213 1214 1215 1216 1217
            goto done;

        /*
         * try though http on port 8000
         */
1218 1219
        if (xenDaemonOpen_tcp(conn, "localhost", "8000") < 0 ||
            xend_detect_config_version(conn) == -1)
1220
            goto failed;
1221
    } else if (STRCASEEQ(conn->uri->scheme, "http")) {
1222
        if (conn->uri->port &&
1223
            virAsprintf(&port, "%d", conn->uri->port) == -1) {
1224
            virReportOOMError();
1225
            goto failed;
1226
        }
1227

1228 1229 1230
        if (xenDaemonOpen_tcp(conn,
                              conn->uri->server ? conn->uri->server : "localhost",
                              port ? port : "8000") < 0 ||
1231
            xend_detect_config_version(conn) == -1)
1232
            goto failed;
1233
    } else {
1234
        virReportError(VIR_ERR_NO_CONNECT, __FUNCTION__);
1235
        goto failed;
1236
    }
1237

1238
 done:
1239
    ret = 0;
1240

1241
failed:
1242 1243
    VIR_FREE(port);
    return ret;
1244
}
1245

1246 1247 1248 1249 1250 1251 1252 1253 1254

/**
 * xenDaemonClose:
 * @conn: an existing virtual connection block
 *
 * This method should be called when a connection to xend instance
 * initialized with xenDaemonOpen is no longer needed
 * to free the associated resources.
 *
1255
 * Returns 0 in case of success, -1 in case of error
1256 1257 1258 1259
 */
int
xenDaemonClose(virConnectPtr conn ATTRIBUTE_UNUSED)
{
1260
    return 0;
1261 1262 1263 1264
}

/**
 * xenDaemonDomainSuspend:
1265 1266
 * @conn: the connection object
 * @def: the domain to suspend
1267 1268 1269 1270 1271 1272 1273
 *
 * Pause the domain, the domain is not scheduled anymore though its resources
 * are preserved. Use xenDaemonDomainResume() to resume execution.
 *
 * Returns 0 in case of success, -1 (with errno) in case of error.
 */
int
1274
xenDaemonDomainSuspend(virConnectPtr conn, virDomainDefPtr def)
1275
{
1276
    if (def->id < 0) {
1277
        virReportError(VIR_ERR_OPERATION_INVALID,
1278
                       _("Domain %s isn't running."), def->name);
1279
        return -1;
1280 1281
    }

1282
    return xend_op(conn, def->name, "op", "pause", NULL);
1283 1284 1285 1286
}

/**
 * xenDaemonDomainResume:
1287 1288
 * @conn: the connection object
 * @def: the domain to resume
1289 1290 1291 1292 1293 1294
 *
 * Resume the domain after xenDaemonDomainSuspend() has been called
 *
 * Returns 0 in case of success, -1 (with errno) in case of error.
 */
int
1295
xenDaemonDomainResume(virConnectPtr conn, virDomainDefPtr def)
1296
{
1297
    if (def->id < 0) {
1298
        virReportError(VIR_ERR_OPERATION_INVALID,
1299
                       _("Domain %s isn't running."), def->name);
1300
        return -1;
1301 1302
    }

1303
    return xend_op(conn, def->name, "op", "unpause", NULL);
1304 1305 1306 1307
}

/**
 * xenDaemonDomainShutdown:
1308 1309
 * @conn: the connection object
 * @def: the domain to shutdown
1310 1311 1312 1313 1314 1315 1316 1317
 *
 * Shutdown the domain, the OS is requested to properly shutdown
 * and the domain may ignore it.  It will return immediately
 * after queuing the request.
 *
 * Returns 0 in case of success, -1 (with errno) in case of error.
 */
int
1318
xenDaemonDomainShutdown(virConnectPtr conn, virDomainDefPtr def)
1319
{
1320
    if (def->id < 0) {
1321
        virReportError(VIR_ERR_OPERATION_INVALID,
1322
                       _("Domain %s isn't running."), def->name);
1323
        return -1;
1324 1325
    }

1326
    return xend_op(conn, def->name, "op", "shutdown", "reason", "poweroff", NULL);
1327 1328
}

1329 1330
/**
 * xenDaemonDomainReboot:
1331 1332
 * @conn: the connection object
 * @def: the domain to reboot
1333 1334 1335 1336 1337 1338 1339 1340
 *
 * Reboot the domain, the OS is requested to properly shutdown
 * and restart but the domain may ignore it.  It will return immediately
 * after queuing the request.
 *
 * Returns 0 in case of success, -1 (with errno) in case of error.
 */
int
1341
xenDaemonDomainReboot(virConnectPtr conn, virDomainDefPtr def)
1342
{
1343
    if (def->id < 0) {
1344
        virReportError(VIR_ERR_OPERATION_INVALID,
1345
                       _("Domain %s isn't running."), def->name);
1346
        return -1;
1347 1348
    }

1349
    return xend_op(conn, def->name, "op", "shutdown", "reason", "reboot", NULL);
1350 1351
}

1352
/**
1353
 * xenDaemonDomainDestroy:
1354 1355
 * @conn: the connection object
 * @def: the domain to destroy
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
 *
 * Abruptly halt the domain, the OS is not properly shutdown and the
 * resources allocated for the domain are immediately freed, mounted
 * filesystems will be marked as uncleanly shutdown.
 * After calling this function, the domain's status will change to
 * dying and will go away completely once all of the resources have been
 * unmapped (usually from the backend devices).
 *
 * Returns 0 in case of success, -1 (with errno) in case of error.
 */
int
1367
xenDaemonDomainDestroy(virConnectPtr conn, virDomainDefPtr def)
1368
{
1369
    if (def->id < 0) {
1370
        virReportError(VIR_ERR_OPERATION_INVALID,
1371
                       _("Domain %s isn't running."), def->name);
1372
        return -1;
1373 1374
    }

1375
    return xend_op(conn, def->name, "op", "destroy", NULL);
1376 1377
}

1378 1379 1380 1381 1382 1383 1384 1385 1386
/**
 * xenDaemonDomainGetOSType:
 * @domain: a domain object
 *
 * Get the type of domain operation system.
 *
 * Returns the new string or NULL in case of error, the string must be
 *         freed by the caller.
 */
1387
char *
1388 1389
xenDaemonDomainGetOSType(virConnectPtr conn,
                         virDomainDefPtr def)
1390 1391 1392 1393 1394
{
    char *type;
    struct sexpr *root;

    /* can we ask for a subset ? worth it ? */
1395
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
1396
    if (root == NULL)
1397
        return NULL;
1398 1399 1400 1401 1402 1403 1404

    if (sexpr_lookup(root, "domain/image/hvm")) {
        type = strdup("hvm");
    } else {
        type = strdup("linux");
    }

1405
    if (type == NULL)
1406
        virReportOOMError();
1407

1408 1409
    sexpr_free(root);

1410
    return type;
1411 1412
}

1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
/**
 * xenDaemonDomainSave:
 * @domain: pointer to the Domain block
 * @filename: path for the output file
 *
 * This method will suspend a domain and save its memory contents to
 * a file on disk.  Use xenDaemonDomainRestore() to restore a domain after
 * saving.
 * Note that for remote Xen Daemon the file path will be interpreted in
 * the remote host.
 *
 * Returns 0 in case of success, -1 (with errno) in case of error.
 */
int
1427 1428 1429
xenDaemonDomainSave(virConnectPtr conn,
                    virDomainDefPtr def,
                    const char *filename)
1430
{
1431
    if (def->id < 0) {
1432
        virReportError(VIR_ERR_OPERATION_INVALID,
1433
                       _("Domain %s isn't running."), def->name);
1434
        return -1;
1435
    }
1436 1437

    /* We can't save the state of Domain-0, that would mean stopping it too */
1438
    if (def->id == 0) {
1439 1440
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Cannot save host domain"));
1441
        return -1;
1442 1443
    }

1444
    return xend_op(conn, def->name, "op", "save", "file", filename, NULL);
1445 1446
}

D
Daniel Veillard 已提交
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
/**
 * xenDaemonDomainCoreDump:
 * @domain: pointer to the Domain block
 * @filename: path for the output file
 * @flags: extra flags, currently unused
 *
 * This method will dump the core of a domain on a given file for analysis.
 * Note that for remote Xen Daemon the file path will be interpreted in
 * the remote host.
 *
 * Returns 0 in case of success, -1 in case of error.
 */
1459
int
1460 1461
xenDaemonDomainCoreDump(virDomainPtr domain,
                        const char *filename,
E
Eric Blake 已提交
1462
                        unsigned int flags)
D
Daniel Veillard 已提交
1463
{
E
Eric Blake 已提交
1464 1465
    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH, -1);

1466
    if (domain->id < 0) {
1467 1468
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Domain %s isn't running."), domain->name);
1469
        return -1;
1470 1471
    }

1472
    return xend_op(domain->conn, domain->name,
J
Jiri Denemark 已提交
1473
                   "op", "dump", "file", filename,
P
Paolo Bonzini 已提交
1474
                   "live", (flags & VIR_DUMP_LIVE ? "1" : "0"),
1475 1476
                   "crash", (flags & VIR_DUMP_CRASH ? "1" : "0"),
                   NULL);
D
Daniel Veillard 已提交
1477 1478
}

1479 1480
/**
 * xenDaemonDomainRestore:
P
Philipp Hahn 已提交
1481
 * @conn: pointer to the Xen Daemon block
1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
 * @filename: path for the output file
 *
 * This method will restore a domain saved to disk by xenDaemonDomainSave().
 * Note that for remote Xen Daemon the file path will be interpreted in
 * the remote host.
 *
 * Returns 0 in case of success, -1 (with errno) in case of error.
 */
int
xenDaemonDomainRestore(virConnectPtr conn, const char *filename)
{
    return xend_op(conn, "", "op", "restore", "file", filename, NULL);
}
1495

1496

1497 1498 1499 1500 1501 1502 1503 1504
/**
 * xenDaemonDomainGetMaxMemory:
 * @domain: pointer to the domain block
 *
 * Ask the Xen Daemon for the maximum memory allowed for a domain
 *
 * Returns the memory size in kilobytes or 0 in case of error.
 */
1505
unsigned long long
1506
xenDaemonDomainGetMaxMemory(virConnectPtr conn, virDomainDefPtr def)
1507
{
1508
    unsigned long long ret = 0;
1509 1510 1511
    struct sexpr *root;

    /* can we ask for a subset ? worth it ? */
1512
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
1513
    if (root == NULL)
1514
        return 0;
1515

1516
    ret = sexpr_u64(root, "domain/memory") << 10;
1517 1518
    sexpr_free(root);

1519
    return ret;
1520 1521
}

1522

1523 1524 1525 1526 1527 1528 1529
/**
 * xenDaemonDomainSetMaxMemory:
 * @domain: pointer to the Domain block
 * @memory: The maximum memory in kilobytes
 *
 * This method will set the maximum amount of memory that can be allocated to
 * a domain.  Please note that a domain is able to allocate up to this amount
1530
 * on its own.
1531 1532 1533 1534
 *
 * Returns 0 for success; -1 (with errno) on error
 */
int
1535 1536 1537
xenDaemonDomainSetMaxMemory(virConnectPtr conn,
                            virDomainDefPtr def,
                            unsigned long memory)
1538 1539
{
    char buf[1024];
1540

1541
    snprintf(buf, sizeof(buf), "%lu", VIR_DIV_UP(memory, 1024));
1542
    return xend_op(conn, def->name, "op", "maxmem_set", "memory",
1543 1544 1545
                   buf, NULL);
}

1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
/**
 * xenDaemonDomainSetMemory:
 * @domain: pointer to the Domain block
 * @memory: The target memory in kilobytes
 *
 * This method will set a target memory allocation for a given domain and
 * request that the guest meet this target.  The guest may or may not actually
 * achieve this target.  When this function returns, it does not signify that
 * the domain has actually reached that target.
 *
 * Memory for a domain can only be allocated up to the maximum memory setting.
 * There is no safe guard for allocations that are too small so be careful
 * when using this function to reduce a domain's memory usage.
 *
 * Returns 0 for success; -1 (with errno) on error
 */
int
1563 1564 1565
xenDaemonDomainSetMemory(virConnectPtr conn,
                         virDomainDefPtr def,
                         unsigned long memory)
1566 1567
{
    char buf[1024];
1568

1569
    snprintf(buf, sizeof(buf), "%lu", VIR_DIV_UP(memory, 1024));
1570
    return xend_op(conn, def->name, "op", "mem_target_set",
1571 1572 1573
                   "target", buf, NULL);
}

1574

1575
virDomainDefPtr
1576
xenDaemonDomainFetch(virConnectPtr conn, int domid, const char *name,
1577
                     const char *cpus)
1578 1579
{
    struct sexpr *root;
1580
    xenUnifiedPrivatePtr priv = conn->privateData;
1581
    virDomainDefPtr def;
1582 1583 1584
    int id;
    char * tty;
    int vncport;
1585

1586 1587 1588 1589
    if (name)
        root = sexpr_get(conn, "/xend/domain/%s?detail=1", name);
    else
        root = sexpr_get(conn, "/xend/domain/%d?detail=1", domid);
1590
    if (root == NULL)
1591
        return NULL;
1592

1593 1594
    id = xenGetDomIdFromSxpr(root, priv->xendConfigVersion);
    xenUnifiedLock(priv);
1595 1596 1597 1598
    if (sexpr_lookup(root, "domain/image/hvm"))
        tty = xenStoreDomainGetSerialConsolePath(conn, id);
    else
        tty = xenStoreDomainGetConsolePath(conn, id);
1599 1600
    vncport = xenStoreDomainGetVNCPort(conn, id);
    xenUnifiedUnlock(priv);
M
Markus Groß 已提交
1601 1602 1603 1604 1605
    if (!(def = xenParseSxpr(root,
                             priv->xendConfigVersion,
                             cpus,
                             tty,
                             vncport)))
1606 1607 1608
        goto cleanup;

cleanup:
1609 1610
    sexpr_free(root);

1611
    return def;
1612 1613 1614
}


1615
/**
1616
 * xenDaemonDomainGetXMLDesc:
D
Daniel Veillard 已提交
1617
 * @domain: a domain object
1618
 * @cpus: list of cpu the domain is pinned to.
D
Daniel Veillard 已提交
1619
 *
1620
 * Get the XML description of the domain as a structure.
D
Daniel Veillard 已提交
1621
 *
1622
 * Returns a virDomainDefPtr instance, or NULL in case of error.
D
Daniel Veillard 已提交
1623
 */
1624 1625 1626
virDomainDefPtr
xenDaemonDomainGetXMLDesc(virConnectPtr conn,
                          virDomainDefPtr minidef,
E
Eric Blake 已提交
1627
                          const char *cpus)
1628
{
1629 1630 1631 1632
    return xenDaemonDomainFetch(conn,
                                minidef->id,
                                minidef->name,
                                cpus);
D
Daniel Veillard 已提交
1633
}
1634

1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646

/**
 * xenDaemonDomainGetInfo:
 * @domain: a domain object
 * @info: pointer to a virDomainInfo structure allocated by the user
 *
 * This method looks up information about a domain and update the
 * information block provided.
 *
 * Returns 0 in case of success, -1 in case of error
 */
int
1647 1648 1649
xenDaemonDomainGetInfo(virConnectPtr conn,
                       virDomainDefPtr def,
                       virDomainInfoPtr info)
1650 1651 1652 1653
{
    struct sexpr *root;
    int ret;

1654
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
1655
    if (root == NULL)
1656
        return -1;
1657

1658
    ret = sexpr_to_xend_domain_info(def, root, info);
1659
    sexpr_free(root);
1660
    return ret;
1661
}
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674


/**
 * xenDaemonDomainGetState:
 * @domain: a domain object
 * @state: returned domain's state
 * @reason: returned reason for the state
 *
 * This method looks up domain state and reason.
 *
 * Returns 0 in case of success, -1 in case of error
 */
int
1675 1676
xenDaemonDomainGetState(virConnectPtr conn,
                        virDomainDefPtr def,
1677
                        int *state,
1678
                        int *reason)
1679 1680 1681
{
    struct sexpr *root;

1682
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
1683 1684 1685
    if (!root)
        return -1;

1686
    *state = sexpr_to_xend_domain_state(def, root);
1687 1688 1689 1690 1691 1692
    if (reason)
        *reason = 0;

    sexpr_free(root);
    return 0;
}
1693

1694

1695
/**
1696
 * xenDaemonLookupByName:
1697 1698 1699 1700 1701 1702 1703
 * @conn: A xend instance
 * @name: The name of the domain
 *
 * This method looks up information about a domain and returns
 * it in the form of a struct xend_domain.  This should be
 * free()'d when no longer needed.
 *
1704
 * Returns domain def pointer on success; NULL on error
1705
 */
1706
virDomainDefPtr
1707
xenDaemonLookupByName(virConnectPtr conn, const char *domname)
1708 1709
{
    struct sexpr *root;
1710
    virDomainDefPtr ret = NULL;
1711 1712 1713 1714 1715 1716 1717 1718 1719

    root = sexpr_get(conn, "/xend/domain/%s?detail=1", domname);
    if (root == NULL)
        goto error;

    ret = sexpr_to_domain(conn, root);

error:
    sexpr_free(root);
1720
    return ret;
1721
}
1722

1723

1724 1725 1726 1727
/**
 * xenDaemonNodeGetInfo:
 * @conn: pointer to the Xen Daemon block
 * @info: pointer to a virNodeInfo structure allocated by the user
1728
 *
1729 1730 1731 1732
 * Extract hardware information about the node.
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
1733
int
1734 1735
xenDaemonNodeGetInfo(virConnectPtr conn, virNodeInfoPtr info)
{
1736 1737 1738 1739 1740
    int ret = -1;
    struct sexpr *root;

    root = sexpr_get(conn, "/xend/node/");
    if (root == NULL)
1741
        return -1;
1742 1743 1744

    ret = sexpr_to_xend_node_info(root, info);
    sexpr_free(root);
1745
    return ret;
1746 1747
}

1748 1749 1750
/**
 * xenDaemonNodeGetTopology:
 * @conn: pointer to the Xen Daemon block
1751
 * @caps: capabilities info
1752 1753 1754 1755 1756 1757
 *
 * This method retrieves a node's topology information.
 *
 * Returns -1 in case of error, 0 otherwise.
 */
int
1758 1759
xenDaemonNodeGetTopology(virConnectPtr conn, virCapsPtr caps)
{
1760 1761 1762 1763 1764
    int ret = -1;
    struct sexpr *root;

    root = sexpr_get(conn, "/xend/node/");
    if (root == NULL) {
1765
        return -1;
1766 1767
    }

1768
    ret = sexpr_to_xend_topology(root, caps);
1769
    sexpr_free(root);
1770
    return ret;
1771 1772
}

1773

1774 1775
/**
 * xenDaemonDomainSetVcpusFlags:
1776 1777
 * @conn: the connection object
 * @def: domain configuration
1778 1779 1780 1781 1782
 * @nvcpus: the new number of virtual CPUs for this domain
 * @flags: bitwise-ORd from virDomainVcpuFlags
 *
 * Change virtual CPUs allocation of domain according to flags.
 *
1783
 * Returns 0 on success, -1 if an error message was issued
1784 1785
 */
int
1786 1787
xenDaemonDomainSetVcpusFlags(virConnectPtr conn,
                             virDomainDefPtr def,
1788
                             unsigned int vcpus,
1789 1790 1791 1792 1793
                             unsigned int flags)
{
    char buf[VIR_UUID_BUFLEN];
    int max;

E
Eric Blake 已提交
1794 1795 1796 1797
    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
                  VIR_DOMAIN_VCPU_CONFIG |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

1798
    if (vcpus < 1) {
1799
        virReportError(VIR_ERR_INVALID_ARG, __FUNCTION__);
1800
        return -1;
1801 1802
    }

1803
    if (def->id < 0) {
1804
        if (flags & VIR_DOMAIN_VCPU_LIVE) {
1805 1806
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("domain not running"));
1807 1808 1809 1810 1811
            return -1;
        }
    } else {
        if ((flags & (VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG)) !=
            (VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG)) {
1812 1813 1814
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Xend only supports modifying both live and "
                             "persistent config"));
1815 1816 1817 1818 1819 1820
        }
    }

    /* Unfortunately, xend_op does not validate whether this exceeds
     * the maximum.  */
    flags |= VIR_DOMAIN_VCPU_MAXIMUM;
1821
    if ((max = xenDaemonDomainGetVcpusFlags(conn, def, flags)) < 0) {
1822 1823
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("could not determine max vcpus for the domain"));
1824 1825 1826
        return -1;
    }
    if (vcpus > max) {
1827 1828 1829
        virReportError(VIR_ERR_INVALID_ARG,
                       _("requested vcpus is greater than max allowable"
                         " vcpus for the domain: %d > %d"), vcpus, max);
1830 1831 1832 1833
        return -1;
    }

    snprintf(buf, sizeof(buf), "%d", vcpus);
1834
    return xend_op(conn, def->name, "op", "set_vcpus", "vcpus",
1835 1836 1837
                   buf, NULL);
}

1838 1839
/**
 * xenDaemonDomainPinCpu:
1840 1841
 * @conn: the connection object
 * @minidef: minimal domain configuration
1842 1843 1844
 * @vcpu: virtual CPU number
 * @cpumap: pointer to a bit map of real CPUs (in 8-bit bytes)
 * @maplen: length of cpumap in bytes
1845
 *
1846
 * Dynamically change the real CPUs which can be allocated to a virtual CPU.
1847 1848 1849 1850 1851
 * NOTE: The XenD cpu affinity map format changed from "[0,1,2]" to
 *       "0,1,2"
 *       the XenD cpu affinity works only after cset 19579.
 *       there is no fine grained xend version detection possible, so we
 *       use the old format for anything before version 3
1852 1853 1854 1855
 *
 * Returns 0 for success; -1 (with errno) on error
 */
int
1856 1857
xenDaemonDomainPinVcpu(virConnectPtr conn,
                       virDomainDefPtr minidef,
1858 1859 1860
                       unsigned int vcpu,
                       unsigned char *cpumap,
                       int maplen)
1861
{
1862
    char buf[VIR_UUID_BUFLEN], mapstr[sizeof(cpumap_t) * 64];
1863
    int i, j, ret;
1864
    xenUnifiedPrivatePtr priv = conn->privateData;
1865
    virDomainDefPtr def = NULL;
1866

1867
    if (maplen > (int)sizeof(cpumap_t)) {
1868
        virReportError(VIR_ERR_INVALID_ARG, __FUNCTION__);
1869
        return -1;
1870
    }
1871

1872
    if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4) {
H
Henrik Persson 已提交
1873 1874
        mapstr[0] = '[';
        mapstr[1] = 0;
1875
    } else {
H
Henrik Persson 已提交
1876
        mapstr[0] = 0;
1877 1878
    }

1879 1880 1881
    /* from bit map, build character string of mapped CPU numbers */
    for (i = 0; i < maplen; i++) for (j = 0; j < 8; j++)
     if (cpumap[i] & (1 << j)) {
1882
        snprintf(buf, sizeof(buf), "%d,", (8 * i) + j);
1883 1884
        strcat(mapstr, buf);
    }
1885
    if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4)
1886 1887 1888 1889
        mapstr[strlen(mapstr) - 1] = ']';
    else
        mapstr[strlen(mapstr) - 1] = 0;

1890
    snprintf(buf, sizeof(buf), "%d", vcpu);
1891

1892
    ret = xend_op(conn, minidef->name, "op", "pincpu", "vcpu", buf,
1893 1894
                  "cpumap", mapstr, NULL);

1895 1896 1897
    if (!(def = xenDaemonDomainFetch(conn,
                                     minidef->id,
                                     minidef->name,
1898 1899 1900 1901
                                     NULL)))
        goto cleanup;

    if (ret == 0) {
H
Hu Tao 已提交
1902 1903 1904 1905 1906 1907 1908
        if (!def->cputune.vcpupin) {
            if (VIR_ALLOC(def->cputune.vcpupin) < 0) {
                virReportOOMError();
                goto cleanup;
            }
            def->cputune.nvcpupin = 0;
        }
1909
        if (virDomainVcpuPinAdd(&def->cputune.vcpupin,
H
Hu Tao 已提交
1910 1911 1912 1913
                                &def->cputune.nvcpupin,
                                cpumap,
                                maplen,
                                vcpu) < 0) {
1914 1915
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("failed to add vcpupin xml entry"));
1916
            return -1;
1917 1918 1919 1920 1921 1922 1923 1924
        }
    }

    return ret;

cleanup:
    virDomainDefFree(def);
    return -1;
1925 1926
}

1927 1928
/**
 * xenDaemonDomainGetVcpusFlags:
1929 1930
 * @conn: the connection object
 * @def: domain configuration
1931 1932 1933 1934 1935
 * @flags: bitwise-ORd from virDomainVcpuFlags
 *
 * Extract information about virtual CPUs of domain according to flags.
 *
 * Returns the number of vcpus on success, -1 if an error message was
1936
 * issued
1937 1938 1939

 */
int
1940 1941 1942
xenDaemonDomainGetVcpusFlags(virConnectPtr conn,
                             virDomainDefPtr def,
                             unsigned int flags)
1943 1944 1945 1946
{
    struct sexpr *root;
    int ret;

E
Eric Blake 已提交
1947 1948 1949 1950
    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
                  VIR_DOMAIN_VCPU_CONFIG |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

1951
    if (def->id < 0 && (flags & VIR_DOMAIN_VCPU_LIVE)) {
1952 1953
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("domain not active"));
1954 1955 1956
        return -1;
    }

1957
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
1958 1959 1960 1961 1962
    if (root == NULL)
        return -1;

    ret = sexpr_int(root, "domain/vcpus");
    if (!(flags & VIR_DOMAIN_VCPU_MAXIMUM)) {
1963
        int vcpus = count_one_bits_l(sexpr_u64(root, "domain/vcpu_avail"));
1964 1965 1966 1967
        if (vcpus)
            ret = MIN(vcpus, ret);
    }
    if (!ret)
1968
        ret = -1;
1969 1970 1971 1972
    sexpr_free(root);
    return ret;
}

1973 1974
/**
 * virDomainGetVcpus:
1975 1976
 * @conn: the connection object
 * @def: domain configuration
1977 1978
 * @info: pointer to an array of virVcpuInfo structures (OUT)
 * @maxinfo: number of structures in info array
E
Eric Blake 已提交
1979
 * @cpumaps: pointer to a bit map of real CPUs for all vcpus of this domain (in 8-bit bytes) (OUT)
D
Daniel Veillard 已提交
1980
 *	If cpumaps is NULL, then no cpumap information is returned by the API.
1981 1982 1983 1984 1985 1986
 *	It's assumed there is <maxinfo> cpumap in cpumaps array.
 *	The memory allocated to cpumaps must be (maxinfo * maplen) bytes
 *	(ie: calloc(maxinfo, maplen)).
 *	One cpumap inside cpumaps has the format described in virDomainPinVcpu() API.
 * @maplen: number of bytes in one cpumap, from 1 up to size of CPU map in
 *	underlying virtualization system (Xen...).
1987
 *
1988
 * Extract information about virtual CPUs of domain, store it in info array
D
Daniel Veillard 已提交
1989
 * and also in cpumaps if this pointer isn't NULL.
1990 1991 1992 1993
 *
 * Returns the number of info filled in case of success, -1 in case of failure.
 */
int
1994 1995
xenDaemonDomainGetVcpus(virConnectPtr conn,
                        virDomainDefPtr def,
1996 1997 1998 1999
                        virVcpuInfoPtr info,
                        int maxinfo,
                        unsigned char *cpumaps,
                        int maplen)
2000 2001 2002 2003 2004 2005 2006
{
    struct sexpr *root, *s, *t;
    virVcpuInfoPtr ipt = info;
    int nbinfo = 0, oln;
    unsigned char *cpumap;
    int vcpu, cpu;

2007
    root = sexpr_get(conn, "/xend/domain/%s?op=vcpuinfo", def->name);
2008
    if (root == NULL)
2009
        return -1;
2010 2011

    if (cpumaps != NULL)
2012
        memset(cpumaps, 0, maxinfo * maplen);
2013 2014

    /* scan the sexprs from "(vcpu (number x)...)" and get parameter values */
2015 2016 2017
    for (s = root; s->kind == SEXPR_CONS; s = s->u.s.cdr) {
        if ((s->u.s.car->kind == SEXPR_CONS) &&
            (s->u.s.car->u.s.car->kind == SEXPR_VALUE) &&
2018
            STREQ(s->u.s.car->u.s.car->u.value, "vcpu")) {
2019
            t = s->u.s.car;
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035
            vcpu = ipt->number = sexpr_int(t, "vcpu/number");
            if ((oln = sexpr_int(t, "vcpu/online")) != 0) {
                if (sexpr_int(t, "vcpu/running")) ipt->state = VIR_VCPU_RUNNING;
                if (sexpr_int(t, "vcpu/blocked")) ipt->state = VIR_VCPU_BLOCKED;
            }
            else
                ipt->state = VIR_VCPU_OFFLINE;
            ipt->cpuTime = sexpr_float(t, "vcpu/cpu_time") * 1000000000;
            ipt->cpu = oln ? sexpr_int(t, "vcpu/cpu") : -1;

            if (cpumaps != NULL && vcpu >= 0 && vcpu < maxinfo) {
                cpumap = (unsigned char *) VIR_GET_CPUMAP(cpumaps, maplen, vcpu);
                /*
                 * get sexpr from "(cpumap (x y z...))" and convert values
                 * to bitmap
                 */
2036 2037 2038
                for (t = t->u.s.cdr; t->kind == SEXPR_CONS; t = t->u.s.cdr)
                    if ((t->u.s.car->kind == SEXPR_CONS) &&
                        (t->u.s.car->u.s.car->kind == SEXPR_VALUE) &&
2039
                        STREQ(t->u.s.car->u.s.car->u.value, "cpumap") &&
2040 2041
                        (t->u.s.car->u.s.cdr->kind == SEXPR_CONS)) {
                        for (t = t->u.s.car->u.s.cdr->u.s.car; t->kind == SEXPR_CONS; t = t->u.s.cdr)
2042
                            if (t->u.s.car->kind == SEXPR_VALUE
2043
                                && virStrToLong_i(t->u.s.car->u.value, NULL, 10, &cpu) == 0
2044 2045 2046
                                && cpu >= 0
                                && (VIR_CPU_MAPLEN(cpu+1) <= maplen)) {
                                VIR_USE_CPU(cpumap, cpu);
2047 2048 2049
                            }
                        break;
                    }
2050 2051
            }

2052 2053 2054
            if (++nbinfo == maxinfo) break;
            ipt++;
        }
2055 2056
    }
    sexpr_free(root);
2057
    return nbinfo;
2058 2059
}

2060 2061 2062 2063 2064 2065 2066
/**
 * xenDaemonLookupByUUID:
 * @conn: pointer to the hypervisor connection
 * @uuid: the raw UUID for the domain
 *
 * Try to lookup a domain on xend based on its UUID.
 *
2067
 * Returns domain def pointer on success; NULL on error
2068
 */
2069
virDomainDefPtr
2070 2071
xenDaemonLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
2072
    virDomainDefPtr ret;
2073 2074
    char *name = NULL;
    int id = -1;
2075
    xenUnifiedPrivatePtr priv = conn->privateData;
2076

2077
    /* Old approach for xen <= 3.0.3 */
2078
    if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4) {
2079 2080 2081 2082 2083 2084
        char **names, **tmp;
        unsigned char ident[VIR_UUID_BUFLEN];
        names = xenDaemonListDomainsOld(conn);
        tmp = names;

        if (names == NULL) {
2085
            return NULL;
2086 2087 2088 2089 2090
        }
        while (*tmp != NULL) {
            id = xenDaemonDomainLookupByName_ids(conn, *tmp, &ident[0]);
            if (id >= 0) {
                if (!memcmp(uuid, ident, VIR_UUID_BUFLEN)) {
E
Eric Blake 已提交
2091
                    name = *tmp;
2092 2093
                    break;
                }
2094
            }
2095
            tmp++;
2096
        }
E
Eric Blake 已提交
2097 2098 2099 2100 2101 2102
        tmp = names;
        while (*tmp) {
            if (*tmp != name)
                VIR_FREE(*tmp);
            tmp++;
        }
2103
        VIR_FREE(names);
2104 2105 2106 2107 2108
    } else { /* New approach for xen >= 3.0.4 */
        char *domname = NULL;
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        struct sexpr *root = NULL;

2109
        virUUIDFormat(uuid, uuidstr);
2110 2111
        root = sexpr_get(conn, "/xend/domain/%s?detail=1", uuidstr);
        if (root == NULL)
2112
            return NULL;
2113 2114 2115 2116 2117
        domname = (char*)sexpr_node(root, "domain/name");
        if (sexpr_node(root, "domain/domid")) /* only active domains have domid */
            id = sexpr_int(root, "domain/domid");
        else
            id = -1;
2118 2119 2120 2121 2122

        if (domname) {
            name = strdup(domname);

            if (name == NULL)
2123
                virReportOOMError();
2124 2125
        }

2126
        sexpr_free(root);
2127 2128 2129
    }

    if (name == NULL)
2130
        return NULL;
2131

2132
    ret = virDomainDefNew(name, uuid, id);
2133

2134
    VIR_FREE(name);
2135
    return ret;
2136
}
2137 2138

/**
2139
 * xenDaemonCreateXML:
2140
 * @conn: pointer to the hypervisor connection
2141
 * @def: domain configuration
2142 2143 2144 2145
 * @flags: an optional set of virDomainFlags
 *
 * Launch a new Linux guest domain, based on an XML description similar
 * to the one returned by virDomainGetXMLDesc()
2146
 * This function may requires privileged access to the hypervisor.
2147
 *
2148 2149
 * Returns a new domain object or NULL in case of failure
 */
2150 2151
int
xenDaemonCreateXML(virConnectPtr conn, virDomainDefPtr def)
2152 2153 2154
{
    int ret;
    char *sexpr;
2155 2156
    const char *tmp;
    struct sexpr *root;
2157
    xenUnifiedPrivatePtr priv = conn->privateData;
2158

2159 2160 2161 2162 2163
    if (def->id != -1) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Domain %s is already running"),
                       def->name);
        return -1;
2164 2165
    }

2166 2167 2168
    if (!(sexpr = xenFormatSxpr(conn, def, priv->xendConfigVersion)))
        return -1;

2169
    ret = xenDaemonDomainCreateXML(conn, sexpr);
2170
    VIR_FREE(sexpr);
2171 2172 2173 2174
    if (ret != 0) {
        goto error;
    }

2175 2176
    /* This comes before wait_for_devices, to ensure that latter
       cleanup will destroy the domain upon failure */
2177 2178
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
    if (root == NULL)
2179 2180
        goto error;

2181 2182 2183 2184 2185 2186 2187 2188 2189 2190
    tmp = sexpr_node(root, "domain/domid");
    if (!tmp) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Domain %s did not start"),
                       def->name);
        goto error;
    }
    if (tmp)
        def->id = sexpr_int(root, "domain/domid");

2191
    if (xend_wait_for_devices(conn, def->name) < 0)
2192 2193
        goto error;

2194
    if (xenDaemonDomainResume(conn, def) < 0)
2195 2196
        goto error;

2197
    virDomainDefFree(def);
2198
    return 0;
2199

2200
  error:
2201
    /* Make sure we don't leave a still-born domain around */
2202
    if (def->id != -1)
2203
        xenDaemonDomainDestroy(conn, def);
2204
    return -1;
2205
}
2206 2207

/**
2208
 * xenDaemonAttachDeviceFlags:
2209 2210
 * @conn: the connection object
 * @minidef: domain configuration
2211
 * @xml: pointer to XML description of device
2212
 * @flags: an OR'ed set of virDomainDeviceModifyFlags
2213
 *
2214 2215 2216 2217 2218
 * Create a virtual device attachment to backend.
 * XML description is translated into S-expression.
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
2219
int
2220 2221
xenDaemonAttachDeviceFlags(virConnectPtr conn,
                           virDomainDefPtr minidef,
2222
                           const char *xml,
2223
                           unsigned int flags)
2224
{
2225
    xenUnifiedPrivatePtr priv = conn->privateData;
2226 2227 2228 2229 2230
    char *sexpr = NULL;
    int ret = -1;
    virDomainDeviceDefPtr dev = NULL;
    virDomainDefPtr def = NULL;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
2231
    char class[8], ref[80];
2232
    char *target = NULL;
2233

E
Eric Blake 已提交
2234 2235
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG, -1);

2236
    if (minidef->id < 0) {
2237 2238
        /* Cannot modify live config if domain is inactive */
        if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
2239 2240
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Cannot modify live config if domain is inactive"));
2241 2242
            return -1;
        }
2243 2244
    } else {
        /* Only live config can be changed if xendConfigVersion < 3 */
2245
        if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4 &&
E
Eric Blake 已提交
2246
            (flags != VIR_DOMAIN_DEVICE_MODIFY_CURRENT &&
2247
             flags != VIR_DOMAIN_DEVICE_MODIFY_LIVE)) {
2248 2249 2250
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Xend version does not support modifying "
                             "persistent config"));
2251 2252
            return -1;
        }
2253
        /* Xen only supports modifying both live and persistent config if
2254 2255
         * xendConfigVersion >= 3
         */
2256
        if (priv->xendConfigVersion >= XEND_CONFIG_VERSION_3_0_4 &&
2257 2258
            (flags != (VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                       VIR_DOMAIN_DEVICE_MODIFY_CONFIG))) {
2259 2260 2261
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Xend only supports modifying both live and "
                             "persistent config"));
2262 2263 2264
            return -1;
        }
    }
2265

2266 2267 2268
    if (!(def = xenDaemonDomainFetch(conn,
                                     minidef->id,
                                     minidef->name,
2269 2270 2271
                                     NULL)))
        goto cleanup;

2272 2273
    if (!(dev = virDomainDeviceDefParse(xml, def, priv->caps, priv->xmlopt,
                                        VIR_DOMAIN_XML_INACTIVE)))
2274 2275 2276 2277 2278
        goto cleanup;


    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
2279 2280 2281 2282
        if (xenFormatSxprDisk(dev->data.disk,
                              &buf,
                              STREQ(def->os.type, "hvm") ? 1 : 0,
                              priv->xendConfigVersion, 1) < 0)
2283
            goto cleanup;
2284 2285 2286 2287 2288 2289 2290

        if (dev->data.disk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
            if (!(target = strdup(dev->data.disk->dst))) {
                virReportOOMError();
                goto cleanup;
            }
        }
2291
        break;
2292 2293

    case VIR_DOMAIN_DEVICE_NET:
2294
        if (xenFormatSxprNet(conn,
M
Markus Groß 已提交
2295 2296 2297 2298
                             dev->data.net,
                             &buf,
                             STREQ(def->os.type, "hvm") ? 1 : 0,
                             priv->xendConfigVersion, 1) < 0)
2299
            goto cleanup;
2300 2301

        char macStr[VIR_MAC_STRING_BUFLEN];
2302
        virMacAddrFormat(&dev->data.net->mac, macStr);
2303 2304 2305 2306 2307

        if (!(target = strdup(macStr))) {
            virReportOOMError();
            goto cleanup;
        }
2308
        break;
2309

2310 2311 2312
    case VIR_DOMAIN_DEVICE_HOSTDEV:
        if (dev->data.hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
            dev->data.hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI) {
M
Markus Groß 已提交
2313
            if (xenFormatSxprOnePCI(dev->data.hostdev, &buf, 0) < 0)
2314
                goto cleanup;
2315

2316
            virDevicePCIAddress PCIAddr;
2317

2318
            PCIAddr = dev->data.hostdev->source.subsys.u.pci.addr;
2319 2320
            if (virAsprintf(&target, "PCI device: %.4x:%.2x:%.2x",
                            PCIAddr.domain, PCIAddr.bus, PCIAddr.slot) < 0) {
2321 2322 2323
                virReportOOMError();
                goto cleanup;
            }
2324
        } else {
2325 2326
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("unsupported device type"));
2327 2328 2329 2330
            goto cleanup;
        }
        break;

2331
    default:
2332 2333
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("unsupported device type"));
2334
        goto cleanup;
2335
    }
2336 2337 2338

    sexpr = virBufferContentAndReset(&buf);

2339
    if (virDomainXMLDevID(conn, minidef, dev, class, ref, sizeof(ref))) {
2340
        /* device doesn't exist, define it */
2341
        ret = xend_op(conn, def->name, "op", "device_create",
2342
                      "config", sexpr, NULL);
2343 2344
    } else {
        if (dev->data.disk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
2345 2346
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("target '%s' already exists"), target);
2347 2348
        } else {
            /* device exists, attempt to modify it */
2349
            ret = xend_op(conn, minidef->name, "op", "device_configure",
2350 2351
                          "config", sexpr, "dev", ref, NULL);
        }
2352
    }
2353 2354

cleanup:
2355
    VIR_FREE(sexpr);
2356 2357
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);
2358
    VIR_FREE(target);
2359 2360 2361
    return ret;
}

2362 2363
/**
 * xenDaemonUpdateDeviceFlags:
2364 2365
 * @conn: the connection object
 * @minidef: domain configuration
2366 2367 2368 2369 2370 2371 2372 2373
 * @xml: pointer to XML description of device
 * @flags: an OR'ed set of virDomainDeviceModifyFlags
 *
 * Create a virtual device attachment to backend.
 * XML description is translated into S-expression.
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
2374
int
2375 2376
xenDaemonUpdateDeviceFlags(virConnectPtr conn,
                           virDomainDefPtr minidef,
2377
                           const char *xml,
2378 2379
                           unsigned int flags)
{
2380
    xenUnifiedPrivatePtr priv = conn->privateData;
2381 2382 2383 2384 2385 2386 2387
    char *sexpr = NULL;
    int ret = -1;
    virDomainDeviceDefPtr dev = NULL;
    virDomainDefPtr def = NULL;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char class[8], ref[80];

E
Eric Blake 已提交
2388
    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_LIVE |
2389 2390
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG, -1);

2391
    if (minidef->id < 0) {
2392 2393
        /* Cannot modify live config if domain is inactive */
        if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
2394 2395
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Cannot modify live config if domain is inactive"));
2396 2397
            return -1;
        }
2398 2399
    } else {
        /* Only live config can be changed if xendConfigVersion < 3 */
2400
        if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4 &&
E
Eric Blake 已提交
2401
            (flags != VIR_DOMAIN_DEVICE_MODIFY_CURRENT &&
2402
             flags != VIR_DOMAIN_DEVICE_MODIFY_LIVE)) {
2403 2404 2405
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Xend version does not support modifying "
                             "persistent config"));
2406 2407 2408 2409 2410
            return -1;
        }
        /* Xen only supports modifying both live and persistent config if
         * xendConfigVersion >= 3
         */
2411
        if (priv->xendConfigVersion >= XEND_CONFIG_VERSION_3_0_4 &&
2412 2413
            (flags != (VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                       VIR_DOMAIN_DEVICE_MODIFY_CONFIG))) {
2414 2415 2416
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Xend only supports modifying both live and "
                             "persistent config"));
2417 2418 2419 2420
            return -1;
        }
    }

2421 2422 2423
    if (!(def = xenDaemonDomainFetch(conn,
                                     minidef->id,
                                     minidef->name,
2424 2425 2426
                                     NULL)))
        goto cleanup;

2427 2428
    if (!(dev = virDomainDeviceDefParse(xml, def, priv->caps, priv->xmlopt,
                                        VIR_DOMAIN_XML_INACTIVE)))
2429 2430 2431 2432 2433
        goto cleanup;


    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
2434
        if (xenFormatSxprDisk(dev->data.disk,
M
Markus Groß 已提交
2435 2436 2437
                              &buf,
                              STREQ(def->os.type, "hvm") ? 1 : 0,
                              priv->xendConfigVersion, 1) < 0)
2438 2439 2440 2441
            goto cleanup;
        break;

    default:
2442 2443
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("unsupported device type"));
2444 2445 2446 2447 2448
        goto cleanup;
    }

    sexpr = virBufferContentAndReset(&buf);

2449
    if (virDomainXMLDevID(conn, minidef, dev, class, ref, sizeof(ref))) {
2450 2451
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("requested device does not exist"));
2452 2453 2454
        goto cleanup;
    } else {
        /* device exists, attempt to modify it */
2455
        ret = xend_op(conn, minidef->name, "op", "device_configure",
2456 2457 2458 2459 2460 2461 2462 2463 2464 2465
                      "config", sexpr, "dev", ref, NULL);
    }

cleanup:
    VIR_FREE(sexpr);
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);
    return ret;
}

2466
/**
2467
 * xenDaemonDetachDeviceFlags:
2468 2469
 * @conn: the connection object
 * @minidef: domain configuration
2470
 * @xml: pointer to XML description of device
2471
 * @flags: an OR'ed set of virDomainDeviceModifyFlags
2472
 *
2473 2474 2475 2476
 * Destroy a virtual device attachment to backend.
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
2477
int
2478 2479
xenDaemonDetachDeviceFlags(virConnectPtr conn,
                           virDomainDefPtr minidef,
2480
                           const char *xml,
2481
                           unsigned int flags)
2482
{
2483
    xenUnifiedPrivatePtr priv = conn->privateData;
2484
    char class[8], ref[80];
2485 2486 2487
    virDomainDeviceDefPtr dev = NULL;
    virDomainDefPtr def = NULL;
    int ret = -1;
2488 2489
    char *xendev = NULL;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
2490

E
Eric Blake 已提交
2491 2492
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG, -1);

2493
    if (minidef->id < 0) {
2494 2495
        /* Cannot modify live config if domain is inactive */
        if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
2496 2497
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Cannot modify live config if domain is inactive"));
2498 2499
            return -1;
        }
2500 2501
    } else {
        /* Only live config can be changed if xendConfigVersion < 3 */
2502
        if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4 &&
E
Eric Blake 已提交
2503
            (flags != VIR_DOMAIN_DEVICE_MODIFY_CURRENT &&
2504
             flags != VIR_DOMAIN_DEVICE_MODIFY_LIVE)) {
2505 2506 2507
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Xend version does not support modifying "
                             "persistent config"));
2508 2509
            return -1;
        }
2510
        /* Xen only supports modifying both live and persistent config if
2511 2512
         * xendConfigVersion >= 3
         */
2513
        if (priv->xendConfigVersion >= XEND_CONFIG_VERSION_3_0_4 &&
2514 2515
            (flags != (VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                       VIR_DOMAIN_DEVICE_MODIFY_CONFIG))) {
2516 2517 2518
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Xend only supports modifying both live and "
                             "persistent config"));
2519 2520 2521
            return -1;
        }
    }
2522

2523 2524 2525
    if (!(def = xenDaemonDomainFetch(conn,
                                     minidef->id,
                                     minidef->name,
2526 2527 2528
                                     NULL)))
        goto cleanup;

2529 2530
    if (!(dev = virDomainDeviceDefParse(xml, def, priv->caps, priv->xmlopt,
                                        VIR_DOMAIN_XML_INACTIVE)))
2531 2532
        goto cleanup;

2533
    if (virDomainXMLDevID(conn, minidef, dev, class, ref, sizeof(ref)))
2534 2535
        goto cleanup;

2536 2537 2538
    if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV) {
        if (dev->data.hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
            dev->data.hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI) {
M
Markus Groß 已提交
2539
            if (xenFormatSxprOnePCI(dev->data.hostdev, &buf, 1) < 0)
2540 2541
                goto cleanup;
        } else {
2542 2543
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("unsupported device type"));
2544 2545 2546
            goto cleanup;
        }
        xendev = virBufferContentAndReset(&buf);
2547
        ret = xend_op(conn, minidef->name, "op", "device_configure",
2548 2549 2550 2551
                      "config", xendev, "dev", ref, NULL);
        VIR_FREE(xendev);
    }
    else {
2552
        ret = xend_op(conn, minidef->name, "op", "device_destroy",
2553 2554 2555
                      "type", class, "dev", ref, "force", "0", "rm_cfg", "1",
                      NULL);
    }
2556 2557 2558 2559 2560 2561

cleanup:
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);

    return ret;
2562
}
2563

2564
int
2565
xenDaemonDomainGetAutostart(virDomainPtr domain, int *autostart)
2566 2567 2568 2569 2570 2571
{
    struct sexpr *root;
    const char *tmp;

    root = sexpr_get(domain->conn, "/xend/domain/%s?detail=1", domain->name);
    if (root == NULL) {
2572 2573
        virReportError(VIR_ERR_XEN_CALL,
                       "%s", _("xenDaemonGetAutostart failed to find this domain"));
2574
        return -1;
2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588
    }

    *autostart = 0;

    tmp = sexpr_node(root, "domain/on_xend_start");
    if (tmp && STREQ(tmp, "start")) {
        *autostart = 1;
    }

    sexpr_free(root);
    return 0;
}

int
2589
xenDaemonDomainSetAutostart(virDomainPtr domain, int autostart)
2590 2591
{
    struct sexpr *root, *autonode;
2592 2593
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    char *content = NULL;
2594 2595 2596 2597
    int ret = -1;

    root = sexpr_get(domain->conn, "/xend/domain/%s?detail=1", domain->name);
    if (root == NULL) {
2598 2599
        virReportError(VIR_ERR_XEN_CALL,
                       "%s", _("xenDaemonSetAutostart failed to find this domain"));
2600
        return -1;
2601 2602
    }

2603 2604 2605 2606
    autonode = sexpr_lookup(root, "domain/on_xend_start");
    if (autonode) {
        const char *val = (autonode->u.s.car->kind == SEXPR_VALUE
                           ? autonode->u.s.car->u.value : NULL);
2607
        if (!val || (!STREQ(val, "ignore") && !STREQ(val, "start"))) {
2608 2609
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("unexpected value from on_xend_start"));
2610 2611 2612
            goto error;
        }

2613
        /* Change the autostart value in place, then define the new sexpr */
2614
        VIR_FREE(autonode->u.s.car->u.value);
2615 2616 2617
        autonode->u.s.car->u.value = (autostart ? strdup("start")
                                                : strdup("ignore"));
        if (!(autonode->u.s.car->u.value)) {
2618
            virReportOOMError();
2619 2620 2621
            goto error;
        }

2622
        if (sexpr2string(root, &buffer) < 0) {
2623 2624
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("sexpr2string failed"));
2625 2626
            goto error;
        }
2627 2628 2629 2630 2631 2632 2633 2634 2635

        if (virBufferError(&buffer)) {
            virReportOOMError();
            goto error;
        }

        content = virBufferContentAndReset(&buffer);

        if (xend_op(domain->conn, "", "op", "new", "config", content, NULL) != 0) {
2636 2637
            virReportError(VIR_ERR_XEN_CALL,
                           "%s", _("Failed to redefine sexpr"));
2638 2639 2640
            goto error;
        }
    } else {
2641 2642
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("on_xend_start not present in sexpr"));
2643 2644 2645 2646 2647
        goto error;
    }

    ret = 0;
  error:
2648 2649
    virBufferFreeAndReset(&buffer);
    VIR_FREE(content);
2650 2651 2652
    sexpr_free(root);
    return ret;
}
2653

2654
int
2655
xenDaemonDomainMigratePrepare(virConnectPtr dconn ATTRIBUTE_UNUSED,
2656 2657 2658 2659 2660 2661 2662
                              char **cookie ATTRIBUTE_UNUSED,
                              int *cookielen ATTRIBUTE_UNUSED,
                              const char *uri_in,
                              char **uri_out,
                              unsigned long flags,
                              const char *dname ATTRIBUTE_UNUSED,
                              unsigned long resource ATTRIBUTE_UNUSED)
2663
{
E
Eric Blake 已提交
2664 2665
    virCheckFlags(XEN_MIGRATION_FLAGS, -1);

2666 2667 2668 2669 2670
    /* If uri_in is NULL, get the current hostname as a best guess
     * of how the source host should connect to us.  Note that caller
     * deallocates this string.
     */
    if (uri_in == NULL) {
2671
        *uri_out = virGetHostname();
2672
        if (*uri_out == NULL)
2673 2674 2675 2676 2677 2678 2679
            return -1;
    }

    return 0;
}

int
2680 2681
xenDaemonDomainMigratePerform(virConnectPtr conn,
                              virDomainDefPtr def,
2682 2683 2684 2685 2686 2687
                              const char *cookie ATTRIBUTE_UNUSED,
                              int cookielen ATTRIBUTE_UNUSED,
                              const char *uri,
                              unsigned long flags,
                              const char *dname,
                              unsigned long bandwidth)
2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698
{
    /* Upper layers have already checked domain. */
    /* NB: Passing port=0 to xend means it ignores
     * the port.  However this is somewhat specific to
     * the internals of the xend Python code. (XXX).
     */
    char port[16] = "0";
    char live[2] = "0";
    int ret;
    char *p, *hostname = NULL;

2699 2700
    int undefined_source = 0;

E
Eric Blake 已提交
2701 2702
    virCheckFlags(XEN_MIGRATION_FLAGS, -1);

2703 2704
    /* Xen doesn't support renaming domains during migration. */
    if (dname) {
2705 2706 2707
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("xenDaemonDomainMigrate: Xen does not support"
                               " renaming domains during migration"));
2708 2709 2710 2711 2712 2713 2714
        return -1;
    }

    /* Xen (at least up to 3.1.0) takes a resource parameter but
     * ignores it.
     */
    if (bandwidth) {
2715 2716 2717
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("xenDaemonDomainMigrate: Xen does not support"
                               " bandwidth limits during migration"));
2718 2719 2720
        return -1;
    }

2721 2722 2723
    /*
     * Check the flags.
     */
2724
    if ((flags & VIR_MIGRATE_LIVE)) {
2725
        strcpy(live, "1");
2726 2727
        flags &= ~VIR_MIGRATE_LIVE;
    }
2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738

    /* Undefine the VM on the source host after migration? */
    if (flags & VIR_MIGRATE_UNDEFINE_SOURCE) {
       undefined_source = 1;
       flags &= ~VIR_MIGRATE_UNDEFINE_SOURCE;
    }

    /* Ignore the persist_dest flag here */
    if (flags & VIR_MIGRATE_PERSIST_DEST)
        flags &= ~VIR_MIGRATE_PERSIST_DEST;

2739 2740 2741 2742
    /* This is buggy in Xend, but could be supported in principle.  Give
     * a nice error message.
     */
    if (flags & VIR_MIGRATE_PAUSED) {
2743 2744
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("xenDaemonDomainMigrate: xend cannot migrate paused domains"));
2745 2746 2747
        return -1;
    }

2748 2749
    /* XXX we could easily do tunnelled & peer2peer migration too
       if we want to. support these... */
2750
    if (flags != 0) {
2751 2752
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("xenDaemonDomainMigrate: unsupported flag"));
2753 2754 2755 2756 2757 2758 2759 2760
        return -1;
    }

    /* Set hostname and port.
     *
     * URI is non-NULL (guaranteed by caller).  We expect either
     * "hostname", "hostname:port" or "xenmigr://hostname[:port]/".
     */
2761
    if (strstr(uri, "//")) {   /* Full URI. */
2762
        virURIPtr uriptr;
2763
        if (!(uriptr = virURIParse(uri)))
2764
            return -1;
2765

2766
        if (uriptr->scheme && STRCASENEQ(uriptr->scheme, "xenmigr")) {
2767 2768 2769
            virReportError(VIR_ERR_INVALID_ARG,
                           "%s", _("xenDaemonDomainMigrate: only xenmigr://"
                                   " migrations are supported by Xen"));
2770
            virURIFree(uriptr);
2771 2772 2773
            return -1;
        }
        if (!uriptr->server) {
2774 2775 2776
            virReportError(VIR_ERR_INVALID_ARG,
                           "%s", _("xenDaemonDomainMigrate: a hostname must be"
                                   " specified in the URI"));
2777
            virURIFree(uriptr);
2778 2779
            return -1;
        }
2780
        hostname = strdup(uriptr->server);
2781
        if (!hostname) {
2782
            virReportOOMError();
2783
            virURIFree(uriptr);
2784 2785 2786
            return -1;
        }
        if (uriptr->port)
2787 2788
            snprintf(port, sizeof(port), "%d", uriptr->port);
        virURIFree(uriptr);
2789
    }
2790
    else if ((p = strrchr(uri, ':')) != NULL) { /* "hostname:port" */
2791 2792
        int port_nr, n;

2793
        if (virStrToLong_i(p+1, NULL, 10, &port_nr) < 0) {
2794 2795
            virReportError(VIR_ERR_INVALID_ARG,
                           "%s", _("xenDaemonDomainMigrate: invalid port number"));
2796 2797
            return -1;
        }
2798
        snprintf(port, sizeof(port), "%d", port_nr);
2799 2800 2801

        /* Get the hostname. */
        n = p - uri; /* n = Length of hostname in bytes. */
2802
        hostname = strdup(uri);
2803
        if (!hostname) {
2804
            virReportOOMError();
2805 2806 2807 2808 2809
            return -1;
        }
        hostname[n] = '\0';
    }
    else {                      /* "hostname" (or IP address) */
2810
        hostname = strdup(uri);
2811
        if (!hostname) {
2812
            virReportOOMError();
2813 2814 2815 2816
            return -1;
        }
    }

2817
    VIR_DEBUG("hostname = %s, port = %s", hostname, port);
2818

J
Jim Fehlig 已提交
2819 2820 2821 2822 2823 2824
    /* Make the call.
     * NB:  xend will fail the operation if any parameters are
     * missing but happily accept unknown parameters.  This works
     * to our advantage since all parameters supported and required
     * by current xend can be included without breaking older xend.
     */
2825
    ret = xend_op(conn, def->name,
2826 2827 2828 2829 2830 2831 2832 2833 2834 2835
                  "op", "migrate",
                  "destination", hostname,
                  "live", live,
                  "port", port,
                  "node", "-1", /* xen-unstable c/s 17753 */
                  "ssl", "0", /* xen-unstable c/s 17709 */
                  "change_home_server", "0", /* xen-unstable c/s 20326 */
                  "resource", "0", /* removed by xen-unstable c/s 17553 */
                  NULL);
    VIR_FREE(hostname);
2836

2837
    if (ret == 0 && undefined_source)
2838
        xenDaemonDomainUndefine(conn, def);
2839

2840
    VIR_DEBUG("migration done");
2841 2842 2843 2844

    return ret;
}

2845 2846
int
xenDaemonDomainDefineXML(virConnectPtr conn, virDomainDefPtr def)
2847
{
2848
    int ret = -1;
2849
    char *sexpr;
2850
    xenUnifiedPrivatePtr priv = conn->privateData;
2851

M
Markus Groß 已提交
2852
    if (!(sexpr = xenFormatSxpr(conn, def, priv->xendConfigVersion))) {
2853 2854
        virReportError(VIR_ERR_XML_ERROR,
                       "%s", _("failed to build sexpr"));
2855
        goto cleanup;
2856 2857
    }

2858
    ret = xend_op(conn, "", "op", "new", "config", sexpr, NULL);
2859
    VIR_FREE(sexpr);
2860
    if (ret != 0) {
2861 2862
        virReportError(VIR_ERR_XEN_CALL,
                       _("Failed to create inactive domain %s"), def->name);
2863
        goto cleanup;
2864 2865
    }

2866
    ret = 0;
2867

2868 2869
cleanup:
    return ret;
2870
}
2871

2872
int
2873 2874
xenDaemonDomainCreate(virConnectPtr conn,
                      virDomainDefPtr def)
2875
{
2876
    int ret;
2877

2878
    ret = xend_op(conn, def->name, "op", "start", NULL);
2879

2880
    if (ret == 0) {
2881 2882
        int id = xenDaemonDomainLookupByName_ids(conn, def->name,
                                                 def->uuid);
2883
        if (id > 0)
2884
            def->id = id;
2885
    }
2886

2887
    return ret;
2888 2889
}

2890
int
2891
xenDaemonDomainUndefine(virConnectPtr conn, virDomainDefPtr def)
2892
{
2893
    return xend_op(conn, def->name, "op", "delete", NULL);
2894 2895 2896 2897 2898 2899 2900 2901 2902 2903
}

/**
 * xenDaemonNumOfDomains:
 * @conn: pointer to the hypervisor connection
 *
 * Provides the number of active domains.
 *
 * Returns the number of domain found or -1 in case of error
 */
2904
int
2905 2906 2907 2908 2909
xenDaemonNumOfDefinedDomains(virConnectPtr conn)
{
    struct sexpr *root = NULL;
    int ret = -1;
    struct sexpr *_for_i, *node;
2910

2911 2912 2913 2914 2915 2916
    root = sexpr_get(conn, "/xend/domain?state=halted");
    if (root == NULL)
        goto error;

    ret = 0;

2917
    /* coverity[copy_paste_error] */
2918 2919
    for (_for_i = root, node = root->u.s.car; _for_i->kind == SEXPR_CONS;
         _for_i = _for_i->u.s.cdr, node = _for_i->u.s.car) {
2920 2921 2922 2923 2924 2925
        if (node->kind != SEXPR_VALUE)
            continue;
        ret++;
    }

error:
2926
    sexpr_free(root);
2927
    return ret;
2928 2929
}

2930
int
2931 2932 2933 2934
xenDaemonListDefinedDomains(virConnectPtr conn,
                            char **const names,
                            int maxnames)
{
2935
    struct sexpr *root = NULL;
2936
    int i, ret = -1;
2937
    struct sexpr *_for_i, *node;
2938

2939
    if (maxnames == 0)
2940
        return 0;
2941

2942 2943 2944 2945 2946 2947
    root = sexpr_get(conn, "/xend/domain?state=halted");
    if (root == NULL)
        goto error;

    ret = 0;

2948
    /* coverity[copy_paste_error] */
2949 2950
    for (_for_i = root, node = root->u.s.car; _for_i->kind == SEXPR_CONS;
         _for_i = _for_i->u.s.cdr, node = _for_i->u.s.car) {
2951 2952 2953
        if (node->kind != SEXPR_VALUE)
            continue;

2954
        if ((names[ret++] = strdup(node->u.value)) == NULL) {
2955
            virReportOOMError();
2956 2957 2958
            goto error;
        }

2959 2960 2961 2962
        if (ret >= maxnames)
            break;
    }

2963 2964
cleanup:
    sexpr_free(root);
2965
    return ret;
2966

2967
error:
2968 2969 2970
    for (i = 0; i < ret; ++i)
        VIR_FREE(names[i]);

2971 2972 2973
    ret = -1;

    goto cleanup;
2974 2975
}

2976 2977 2978 2979 2980 2981 2982 2983 2984 2985
/**
 * xenDaemonGetSchedulerType:
 * @domain: pointer to the Domain block
 * @nparams: give a number of scheduler parameters
 *
 * Get the scheduler type of Xen
 *
 * Returns a scheduler name (credit or sedf) which must be freed by the
 * caller or NULL in case of failure
 */
2986
char *
2987 2988
xenDaemonGetSchedulerType(virDomainPtr domain, int *nparams)
{
2989
    xenUnifiedPrivatePtr priv = domain->conn->privateData;
2990 2991 2992 2993 2994
    struct sexpr *root;
    const char *ret = NULL;
    char *schedulertype = NULL;

    /* Support only xendConfigVersion >=4 */
2995
    if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_1_0) {
2996 2997
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("unsupported in xendConfigVersion < 4"));
2998 2999 3000 3001 3002 3003 3004 3005 3006 3007
        return NULL;
    }

    root = sexpr_get(domain->conn, "/xend/node/");
    if (root == NULL)
        return NULL;

    /* get xen_scheduler from xend/node */
    ret = sexpr_node(root, "node/xen_scheduler");
    if (ret == NULL){
3008 3009
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("node information incomplete, missing scheduler name"));
3010 3011
        goto error;
    }
3012
    if (STREQ(ret, "credit")) {
3013 3014
        schedulertype = strdup("credit");
        if (schedulertype == NULL){
3015
            virReportOOMError();
3016 3017
            goto error;
        }
3018 3019
        if (nparams)
            *nparams = XEN_SCHED_CRED_NPARAM;
3020
    } else if (STREQ(ret, "sedf")) {
3021 3022
        schedulertype = strdup("sedf");
        if (schedulertype == NULL){
3023
            virReportOOMError();
3024 3025
            goto error;
        }
3026 3027
        if (nparams)
            *nparams = XEN_SCHED_SEDF_NPARAM;
3028
    } else {
3029
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Unknown scheduler"));
3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050
        goto error;
    }

error:
    sexpr_free(root);
    return schedulertype;

}

/**
 * xenDaemonGetSchedulerParameters:
 * @domain: pointer to the Domain block
 * @params: pointer to scheduler parameters
 *          This memory area must be allocated by the caller
 * @nparams: a number of scheduler parameters which should be same as a
 *           given number from xenDaemonGetSchedulerType()
 *
 * Get the scheduler parameters
 *
 * Returns 0 or -1 in case of failure
 */
3051
int
3052
xenDaemonGetSchedulerParameters(virDomainPtr domain,
3053 3054
                                virTypedParameterPtr params,
                                int *nparams)
3055
{
3056
    xenUnifiedPrivatePtr priv = domain->conn->privateData;
3057 3058 3059 3060 3061 3062
    struct sexpr *root;
    char *sched_type = NULL;
    int sched_nparam = 0;
    int ret = -1;

    /* Support only xendConfigVersion >=4 */
3063
    if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_1_0) {
3064 3065
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("unsupported in xendConfigVersion < 4"));
3066
        return -1;
3067 3068 3069 3070 3071
    }

    /* look up the information by domain name */
    root = sexpr_get(domain->conn, "/xend/domain/%s?detail=1", domain->name);
    if (root == NULL)
3072
        return -1;
3073 3074 3075 3076

    /* get the scheduler type */
    sched_type = xenDaemonGetSchedulerType(domain, &sched_nparam);
    if (sched_type == NULL) {
3077 3078
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("Failed to get a scheduler name"));
3079 3080 3081 3082 3083
        goto error;
    }

    switch (sched_nparam){
        case XEN_SCHED_SEDF_NPARAM:
3084
            if (*nparams < XEN_SCHED_SEDF_NPARAM) {
3085 3086
                virReportError(VIR_ERR_INVALID_ARG,
                               "%s", _("Invalid parameter count"));
3087 3088 3089
                goto error;
            }

3090 3091 3092 3093 3094 3095
            /* TODO: Implement for Xen/SEDF */
            TODO
            goto error;
        case XEN_SCHED_CRED_NPARAM:
            /* get cpu_weight/cpu_cap from xend/domain */
            if (sexpr_node(root, "domain/cpu_weight") == NULL) {
3096 3097
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               "%s", _("domain information incomplete, missing cpu_weight"));
3098 3099 3100
                goto error;
            }
            if (sexpr_node(root, "domain/cpu_cap") == NULL) {
3101 3102
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               "%s", _("domain information incomplete, missing cpu_cap"));
3103 3104 3105
                goto error;
            }

3106 3107
            if (virStrcpyStatic(params[0].field,
                                VIR_DOMAIN_SCHEDULER_WEIGHT) == NULL) {
3108 3109 3110
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Weight %s too big for destination"),
                               VIR_DOMAIN_SCHEDULER_WEIGHT);
C
Chris Lalancette 已提交
3111 3112
                goto error;
            }
3113
            params[0].type = VIR_TYPED_PARAM_UINT;
3114 3115
            params[0].value.ui = sexpr_int(root, "domain/cpu_weight");

3116 3117 3118
            if (*nparams > 1) {
                if (virStrcpyStatic(params[1].field,
                                    VIR_DOMAIN_SCHEDULER_CAP) == NULL) {
3119 3120 3121
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Cap %s too big for destination"),
                                   VIR_DOMAIN_SCHEDULER_CAP);
3122 3123 3124 3125
                    goto error;
                }
                params[1].type = VIR_TYPED_PARAM_UINT;
                params[1].value.ui = sexpr_int(root, "domain/cpu_cap");
C
Chris Lalancette 已提交
3126
            }
3127 3128 3129

            if (*nparams > XEN_SCHED_CRED_NPARAM)
                *nparams = XEN_SCHED_CRED_NPARAM;
3130 3131 3132
            ret = 0;
            break;
        default:
3133
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Unknown scheduler"));
3134 3135 3136 3137 3138
            goto error;
    }

error:
    sexpr_free(root);
3139
    VIR_FREE(sched_type);
3140
    return ret;
3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152
}

/**
 * xenDaemonSetSchedulerParameters:
 * @domain: pointer to the Domain block
 * @params: pointer to scheduler parameters
 * @nparams: a number of scheduler setting parameters
 *
 * Set the scheduler parameters
 *
 * Returns 0 or -1 in case of failure
 */
3153
int
3154
xenDaemonSetSchedulerParameters(virDomainPtr domain,
3155 3156
                                virTypedParameterPtr params,
                                int nparams)
3157
{
3158
    xenUnifiedPrivatePtr priv = domain->conn->privateData;
3159 3160 3161 3162 3163 3164 3165
    struct sexpr *root;
    char *sched_type = NULL;
    int i;
    int sched_nparam = 0;
    int ret = -1;

    /* Support only xendConfigVersion >=4 and active domains */
3166
    if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_1_0) {
3167 3168
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("unsupported in xendConfigVersion < 4"));
3169
        return -1;
3170 3171 3172 3173 3174
    }

    /* look up the information by domain name */
    root = sexpr_get(domain->conn, "/xend/domain/%s?detail=1", domain->name);
    if (root == NULL)
3175
        return -1;
3176 3177 3178 3179

    /* get the scheduler type */
    sched_type = xenDaemonGetSchedulerType(domain, &sched_nparam);
    if (sched_type == NULL) {
3180 3181
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("Failed to get a scheduler name"));
3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199
        goto error;
    }

    switch (sched_nparam){
        case XEN_SCHED_SEDF_NPARAM:
            /* TODO: Implement for Xen/SEDF */
            TODO
            goto error;
        case XEN_SCHED_CRED_NPARAM: {
            char buf_weight[VIR_UUID_BUFLEN];
            char buf_cap[VIR_UUID_BUFLEN];
            const char *weight = NULL;
            const char *cap = NULL;

            /* get the scheduler parameters */
            memset(&buf_weight, 0, VIR_UUID_BUFLEN);
            memset(&buf_cap, 0, VIR_UUID_BUFLEN);
            for (i = 0; i < nparams; i++) {
3200
                if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_WEIGHT) &&
3201
                    params[i].type == VIR_TYPED_PARAM_UINT) {
3202
                    snprintf(buf_weight, sizeof(buf_weight), "%u", params[i].value.ui);
3203
                } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_CAP) &&
3204
                    params[i].type == VIR_TYPED_PARAM_UINT) {
3205 3206
                    snprintf(buf_cap, sizeof(buf_cap), "%u", params[i].value.ui);
                } else {
3207
                    virReportError(VIR_ERR_INVALID_ARG, __FUNCTION__);
3208 3209 3210 3211 3212 3213 3214 3215
                    goto error;
                }
            }

            /* if not get the scheduler parameter, set the current setting */
            if (strlen(buf_weight) == 0) {
                weight = sexpr_node(root, "domain/cpu_weight");
                if (weight == NULL) {
3216 3217
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("domain information incomplete, missing cpu_weight"));
3218 3219 3220 3221 3222 3223 3224
                    goto error;
                }
                snprintf(buf_weight, sizeof(buf_weight), "%s", weight);
            }
            if (strlen(buf_cap) == 0) {
                cap = sexpr_node(root, "domain/cpu_cap");
                if (cap == NULL) {
3225 3226
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("domain information incomplete, missing cpu_cap"));
3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237
                    goto error;
                }
                snprintf(buf_cap, sizeof(buf_cap), "%s", cap);
            }

            ret = xend_op(domain->conn, domain->name, "op",
                          "domain_sched_credit_set", "weight", buf_weight,
                          "cap", buf_cap, NULL);
            break;
        }
        default:
3238
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Unknown scheduler"));
3239 3240 3241 3242 3243
            goto error;
    }

error:
    sexpr_free(root);
3244
    VIR_FREE(sched_type);
3245
    return ret;
3246 3247
}

R
Richard W.M. Jones 已提交
3248 3249
/**
 * xenDaemonDomainBlockPeek:
P
Philipp Hahn 已提交
3250
 * @domain: domain object
R
Richard W.M. Jones 已提交
3251 3252 3253 3254 3255
 * @path: path to the file or device
 * @offset: offset
 * @size: size
 * @buffer: return buffer
 *
3256
 * Returns 0 if successful, -1 if error
R
Richard W.M. Jones 已提交
3257 3258
 */
int
3259 3260 3261 3262
xenDaemonDomainBlockPeek(virDomainPtr domain,
                         const char *path,
                         unsigned long long offset,
                         size_t size,
3263
                         void *buffer)
R
Richard W.M. Jones 已提交
3264
{
3265
    xenUnifiedPrivatePtr priv = domain->conn->privateData;
3266 3267 3268
    struct sexpr *root = NULL;
    int fd = -1, ret = -1;
    virDomainDefPtr def;
3269 3270 3271
    int id;
    char * tty;
    int vncport;
3272
    const char *actual;
R
Richard W.M. Jones 已提交
3273 3274 3275

    /* Security check: The path must correspond to a block device. */
    if (domain->id > 0)
3276 3277
        root = sexpr_get(domain->conn, "/xend/domain/%d?detail=1",
                         domain->id);
R
Richard W.M. Jones 已提交
3278
    else if (domain->id < 0)
3279 3280
        root = sexpr_get(domain->conn, "/xend/domain/%s?detail=1",
                         domain->name);
R
Richard W.M. Jones 已提交
3281 3282
    else {
        /* This call always fails for dom0. */
3283 3284
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domainBlockPeek is not supported for dom0"));
R
Richard W.M. Jones 已提交
3285 3286 3287 3288
        return -1;
    }

    if (!root) {
3289
        virReportError(VIR_ERR_XEN_CALL, __FUNCTION__);
R
Richard W.M. Jones 已提交
3290 3291 3292
        return -1;
    }

3293 3294 3295 3296 3297 3298
    id = xenGetDomIdFromSxpr(root, priv->xendConfigVersion);
    xenUnifiedLock(priv);
    tty = xenStoreDomainGetConsolePath(domain->conn, id);
    vncport = xenStoreDomainGetVNCPort(domain->conn, id);
    xenUnifiedUnlock(priv);

M
Markus Groß 已提交
3299 3300
    if (!(def = xenParseSxpr(root, priv->xendConfigVersion, NULL, tty,
                             vncport)))
3301
        goto cleanup;
R
Richard W.M. Jones 已提交
3302

3303
    if (!(actual = virDomainDiskPathByName(def, path))) {
3304 3305
        virReportError(VIR_ERR_INVALID_ARG,
                       _("%s: invalid path"), path);
3306
        goto cleanup;
R
Richard W.M. Jones 已提交
3307
    }
3308
    path = actual;
R
Richard W.M. Jones 已提交
3309 3310

    /* The path is correct, now try to open it and get its size. */
3311
    fd = open(path, O_RDONLY);
3312
    if (fd == -1) {
3313
        virReportSystemError(errno,
3314 3315
                             _("failed to open for reading: %s"),
                             path);
3316
        goto cleanup;
R
Richard W.M. Jones 已提交
3317 3318 3319 3320 3321 3322
    }

    /* Seek and read. */
    /* NB. Because we configure with AC_SYS_LARGEFILE, off_t should
     * be 64 bits on all platforms.
     */
3323 3324
    if (lseek(fd, offset, SEEK_SET) == (off_t) -1 ||
        saferead(fd, buffer, size) == (ssize_t) -1) {
3325
        virReportSystemError(errno,
3326 3327
                             _("failed to lseek or read from file: %s"),
                             path);
3328
        goto cleanup;
R
Richard W.M. Jones 已提交
3329 3330 3331
    }

    ret = 0;
3332
 cleanup:
3333
    VIR_FORCE_CLOSE(fd);
3334 3335
    sexpr_free(root);
    virDomainDefFree(def);
R
Richard W.M. Jones 已提交
3336 3337 3338
    return ret;
}

3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350

/**
 * virDomainXMLDevID:
 * @domain: pointer to domain object
 * @dev: pointer to device config object
 * @class: Xen device class "vbd" or "vif" (OUT)
 * @ref: Xen device reference (OUT)
 *
 * Set class according to XML root, and:
 *  - if disk, copy in ref the target name from description
 *  - if network, get MAC address from description, scan XenStore and
 *    copy in ref the corresponding vif number.
3351 3352
 *  - if pci, get BDF from description, scan XenStore and
 *    copy in ref the corresponding dev number.
3353 3354 3355 3356
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
static int
3357 3358
virDomainXMLDevID(virConnectPtr conn,
                  virDomainDefPtr def,
3359 3360 3361 3362 3363
                  virDomainDeviceDefPtr dev,
                  char *class,
                  char *ref,
                  int ref_len)
{
3364
    xenUnifiedPrivatePtr priv = conn->privateData;
3365
    char *xref;
C
Chris Lalancette 已提交
3366
    char *tmp;
3367 3368

    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
3369 3370 3371
        if (dev->data.disk->driverName &&
            STREQ(dev->data.disk->driverName, "tap"))
            strcpy(class, "tap");
J
Jim Fehlig 已提交
3372 3373 3374
        else if (dev->data.disk->driverName &&
            STREQ(dev->data.disk->driverName, "tap2"))
            strcpy(class, "tap2");
3375 3376 3377
        else
            strcpy(class, "vbd");

3378 3379
        if (dev->data.disk->dst == NULL)
            return -1;
D
Daniel P. Berrange 已提交
3380
        xenUnifiedLock(priv);
3381
        xref = xenStoreDomainGetDiskID(conn, def->id,
3382
                                       dev->data.disk->dst);
D
Daniel P. Berrange 已提交
3383
        xenUnifiedUnlock(priv);
3384 3385 3386
        if (xref == NULL)
            return -1;

C
Chris Lalancette 已提交
3387
        tmp = virStrcpy(ref, xref, ref_len);
3388
        VIR_FREE(xref);
C
Chris Lalancette 已提交
3389 3390
        if (tmp == NULL)
            return -1;
3391
    } else if (dev->type == VIR_DOMAIN_DEVICE_NET) {
3392
        char mac[VIR_MAC_STRING_BUFLEN];
3393 3394
        virDomainNetDefPtr netdef = dev->data.net;
        virMacAddrFormat(&netdef->mac, mac);
3395 3396 3397

        strcpy(class, "vif");

D
Daniel P. Berrange 已提交
3398
        xenUnifiedLock(priv);
3399
        xref = xenStoreDomainGetNetworkID(conn, def->id, mac);
D
Daniel P. Berrange 已提交
3400
        xenUnifiedUnlock(priv);
3401 3402 3403
        if (xref == NULL)
            return -1;

C
Chris Lalancette 已提交
3404
        tmp = virStrcpy(ref, xref, ref_len);
3405
        VIR_FREE(xref);
C
Chris Lalancette 已提交
3406 3407
        if (tmp == NULL)
            return -1;
3408 3409 3410
    } else if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV &&
               dev->data.hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
               dev->data.hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI) {
3411
        char *bdf;
3412
        virDomainHostdevDefPtr hostdef = dev->data.hostdev;
3413 3414

        if (virAsprintf(&bdf, "%04x:%02x:%02x.%0x",
3415 3416 3417 3418
                        hostdef->source.subsys.u.pci.addr.domain,
                        hostdef->source.subsys.u.pci.addr.bus,
                        hostdef->source.subsys.u.pci.addr.slot,
                        hostdef->source.subsys.u.pci.addr.function) < 0) {
3419
            virReportOOMError();
3420 3421 3422 3423 3424 3425
            return -1;
        }

        strcpy(class, "pci");

        xenUnifiedLock(priv);
3426
        xref = xenStoreDomainGetPCIID(conn, def->id, bdf);
3427 3428 3429 3430 3431 3432 3433 3434 3435
        xenUnifiedUnlock(priv);
        VIR_FREE(bdf);
        if (xref == NULL)
            return -1;

        tmp = virStrcpy(ref, xref, ref_len);
        VIR_FREE(xref);
        if (tmp == NULL)
            return -1;
3436
    } else {
3437 3438
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("hotplug of device type not supported"));
3439 3440 3441 3442 3443
        return -1;
    }

    return 0;
}