xend_internal.c 98.1 KB
Newer Older
1 2 3
/*
 * xend_internal.c: access to Xen though the Xen Daemon interface
 *
4
 * Copyright (C) 2010-2014 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
VIR_LOG_INIT("xen.xend_internal");

68 69 70
/*
 * The number of Xen scheduler parameters
 */
71

72
#define XEND_RCV_BUF_MAX_LEN (256 * 1024)
D
Daniel Veillard 已提交
73

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

79 80 81 82 83 84 85 86 87
/**
 * 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
88
do_connect(virConnectPtr xend)
89 90
{
    int s;
91
    int no_slow_start = 1;
92
    xenUnifiedPrivatePtr priv = xend->privateData;
93

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

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

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

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

    return s;
}

/**
 * wr_sync:
125
 * @xend: the xend connection object
126 127 128 129 130 131 132 133 134 135
 * @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
136
wr_sync(int fd, void *buffer, size_t size, int do_read)
137 138 139 140 141 142 143
{
    size_t offset = 0;

    while (offset < size) {
        ssize_t len;

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

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

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

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

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

        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
188
sread(int fd, void *buffer, size_t size)
189
{
190
    return wr_sync(fd, buffer, size, 1);
191 192 193 194 195 196 197 198 199 200 201 202 203
}

/**
 * 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
204
swrite(int fd, const void *buffer, size_t size)
205
{
206
    return wr_sync(fd, (void *) buffer, size, 0);
207 208 209 210 211 212 213 214 215 216 217 218
}

/**
 * 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
219
swrites(int fd, const char *string)
220
{
221
    return swrite(fd, string, strlen(string));
222 223
}

224 225 226 227 228 229 230 231 232 233 234
/**
 * 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
235
sreads(int fd, char *buffer, size_t n_buffer)
236 237 238 239
{
    size_t offset;

    if (n_buffer < 1)
240
        return -1;
241 242 243 244

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

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

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

    return offset;
}
260 261 262 263

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

267

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

289
    if (VIR_ALLOC_N(buffer, buffer_size) < 0)
290 291 292
        return -1;

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

P
Peter Krempa 已提交
296
        if (istartswith(buffer, "Content-Length: ")) {
J
Jim Fehlig 已提交
297
            if (virStrToLong_i(buffer + 16, &end_ptr, 10, &content_length) < 0) {
P
Peter Krempa 已提交
298 299 300 301 302
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("failed to parse Xend response content length"));
                return -1;
            }
        } else if (istartswith(buffer, "HTTP/1.1 ")) {
J
Jim Fehlig 已提交
303
            if (virStrToLong_i(buffer + 9, &end_ptr, 10, &retcode) < 0) {
P
Peter Krempa 已提交
304 305 306 307 308
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("failed to parse Xend response return code"));
                return -1;
            }
        }
309 310
    }

311 312
    VIR_FREE(buffer);

313
    if (content_length > 0) {
314 315
        ssize_t ret;

J
Jim Fehlig 已提交
316
        if (content_length > XEND_RCV_BUF_MAX_LEN) {
317 318 319 320 321
            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 已提交
322 323 324 325 326 327
            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. */
328
        if (VIR_ALLOC_N(*content, content_length + 1) < 0)
329
            return -1;
330

331
        ret = sread(fd, *content, content_length);
332 333
        if (ret < 0)
            return -1;
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
    }

    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 已提交
349
static int ATTRIBUTE_NONNULL(3)
350
xend_get(virConnectPtr xend, const char *path, char **content)
351 352 353 354 355 356 357
{
    int ret;
    int s = do_connect(xend);

    if (s == -1)
        return s;

358 359 360
    swrites(s, "GET ");
    swrites(s, path);
    swrites(s, " HTTP/1.1\r\n");
361

362
    swrites(s,
363 364 365 366
            "Host: localhost:8000\r\n"
            "Accept-Encoding: identity\r\n"
            "Content-Type: application/x-www-form-urlencoded\r\n" "\r\n");

367
    ret = xend_req(s, content);
368
    VIR_FORCE_CLOSE(s);
369

370 371 372 373
    if (ret < 0)
        return ret;

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

379 380 381 382 383 384 385
    return ret;
}

/**
 * xend_post:
 * @xend: pointer to the Xen Daemon structure
 * @path: the path used for the HTTP request
386
 * @ops: the information sent for the POST
387 388 389 390 391 392 393
 *
 * 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
394
xend_post(virConnectPtr xend, const char *path, const char *ops)
395 396
{
    char buffer[100];
397
    char *err_buf = NULL;
398 399 400 401 402 403
    int ret;
    int s = do_connect(xend);

    if (s == -1)
        return s;

404 405 406
    swrites(s, "POST ");
    swrites(s, path);
    swrites(s, " HTTP/1.1\r\n");
407

408
    swrites(s,
409 410 411 412
            "Host: localhost:8000\r\n"
            "Accept-Encoding: identity\r\n"
            "Content-Type: application/x-www-form-urlencoded\r\n"
            "Content-Length: ");
413
    snprintf(buffer, sizeof(buffer), "%d", (int) strlen(ops));
414 415 416
    swrites(s, buffer);
    swrites(s, "\r\n\r\n");
    swrites(s, ops);
417

418
    ret = xend_req(s, &err_buf);
419
    VIR_FORCE_CLOSE(s);
420

D
Daniel Veillard 已提交
421
    if ((ret < 0) || (ret >= 300)) {
422 423
        virReportError(VIR_ERR_POST_FAILED,
                       _("xend_post: error from xen daemon: %s"), err_buf);
424
    } else if ((ret == 202) && err_buf && (strstr(err_buf, "failed") != NULL)) {
425 426
        virReportError(VIR_ERR_POST_FAILED,
                       _("xend_post: error from xen daemon: %s"), err_buf);
427
        ret = -1;
428 429
    } else if (((ret >= 200) && (ret <= 202)) && err_buf &&
               (strstr(err_buf, "xend.err") != NULL)) {
430 431 432
        /* 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 :-(
433
         */
434 435
        virReportError(VIR_ERR_POST_FAILED,
                       _("xend_post: error from xen daemon: %s"), err_buf);
436
        ret = -1;
D
Daniel Veillard 已提交
437 438
    }

439
    VIR_FREE(err_buf);
440 441
    return ret;
}
442

443 444 445 446 447 448 449 450 451 452

/**
 * 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
453
http2unix(int ret)
454 455 456 457 458 459 460 461 462 463 464
{
    switch (ret) {
        case -1:
            break;
        case 200:
        case 201:
        case 202:
            return 0;
        case 404:
            errno = ESRCH;
            break;
465 466 467
        case 500:
            errno = EIO;
            break;
468
        default:
469 470
            virReportError(VIR_ERR_HTTP_ERROR,
                           _("Unexpected HTTP error code %d"), ret);
471 472 473 474 475 476 477
            errno = EINVAL;
            break;
    }
    return -1;
}

/**
478
 * xend_op_ext:
479 480 481 482 483 484 485 486 487 488
 * @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
489
xend_op_ext(virConnectPtr xend, const char *path, const char *key, va_list ap)
490 491
{
    const char *k = key, *v;
492
    virBuffer buf = VIR_BUFFER_INITIALIZER;
493
    int ret;
494
    char *content;
495 496 497 498

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

P
Philipp Hahn 已提交
499 500 501
        virBufferURIEncodeString(&buf, k);
        virBufferAddChar(&buf, '=');
        virBufferURIEncodeString(&buf, v);
502 503 504
        k = va_arg(ap, const char *);

        if (k)
505
            virBufferAddChar(&buf, '&');
506 507
    }

508
    if (virBufferError(&buf)) {
509
        virBufferFreeAndReset(&buf);
510
        virReportOOMError();
511 512 513 514
        return -1;
    }

    content = virBufferContentAndReset(&buf);
515
    VIR_DEBUG("xend op: %s\n", content);
516
    ret = http2unix(xend_post(xend, path, content));
517
    VIR_FREE(content);
518 519

    return ret;
520 521
}

522

523
/**
524
 * xend_op:
525 526 527 528 529 530 531 532 533 534 535
 * @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 已提交
536
static int ATTRIBUTE_SENTINEL
537
xend_op(virConnectPtr xend, const char *name, const char *key, ...)
538 539 540 541 542 543 544 545
{
    char buffer[1024];
    va_list ap;
    int ret;

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

    va_start(ap, key);
546
    ret = xend_op_ext(xend, buffer, key, ap);
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
    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
 */
563
static struct sexpr *sexpr_get(virConnectPtr xend, const char *fmt, ...)
E
Eric Blake 已提交
564
  ATTRIBUTE_FMT_PRINTF(2, 3);
565

566
static struct sexpr *
567
sexpr_get(virConnectPtr xend, const char *fmt, ...)
568
{
569
    char *buffer = NULL;
570 571 572
    char path[1024];
    va_list ap;
    int ret;
573
    struct sexpr *res = NULL;
574 575 576 577 578

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

579
    ret = xend_get(xend, path, &buffer);
580
    ret = http2unix(ret);
581
    if (ret == -1)
582 583 584 585 586 587
        goto cleanup;

    if (buffer == NULL)
        goto cleanup;

    res = string2sexpr(buffer);
588

589
 cleanup:
590 591
    VIR_FREE(buffer);
    return res;
592 593 594 595 596 597 598 599
}

/**
 * sexpr_uuid:
 * @ptr: where to store the UUID, incremented
 * @sexpr: an S-Expression
 * @name: the name for the value
 *
N
Nehal J Wani 已提交
600
 * convenience function to lookup a UUID value from the S-Expression
601
 *
602
 * Returns a -1 on error, 0 on success
603
 */
604
static int
605
sexpr_uuid(unsigned char *ptr, const struct sexpr *node, const char *path)
606 607
{
    const char *r = sexpr_node(node, path);
608 609 610
    if (!r)
        return -1;
    return virUUIDParse(r, ptr);
611 612 613 614 615
}

/* PUBLIC FUNCTIONS */

/**
616
 * xenDaemonOpen_unix:
617
 * @conn: an existing virtual connection block
618 619 620 621 622
 * @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
 *
623
 * Returns 0 in case of success, -1 in case of error.
624
 */
625
int
626
xenDaemonOpen_unix(virConnectPtr conn, const char *path)
627 628
{
    struct sockaddr_un *addr;
629
    xenUnifiedPrivatePtr priv = conn->privateData;
630

631 632
    memset(&priv->addr, 0, sizeof(priv->addr));
    priv->addrfamily = AF_UNIX;
633 634 635 636 637
    /*
     * This must be zero on Solaris at least for AF_UNIX (which should
     * really be PF_UNIX, but doesn't matter).
     */
    priv->addrprotocol = 0;
638 639 640
    priv->addrlen = sizeof(struct sockaddr_un);

    addr = (struct sockaddr_un *)&priv->addr;
641 642
    addr->sun_family = AF_UNIX;
    memset(addr->sun_path, 0, sizeof(addr->sun_path));
C
Chris Lalancette 已提交
643 644
    if (virStrcpyStatic(addr->sun_path, path) == NULL)
        return -1;
645

646
    return 0;
647 648
}

649

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

670 671 672
    priv->addrlen = 0;
    memset(&priv->addr, 0, sizeof(priv->addr));

673
    /* http://people.redhat.com/drepper/userapi-ipv6.html */
674
    memset (&hints, 0, sizeof(hints));
675 676 677 678 679
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_ADDRCONFIG;

    ret = getaddrinfo (host, port, &hints, &res);
    if (ret != 0) {
680 681 682
        virReportError(VIR_ERR_UNKNOWN_HOST,
                       _("unable to resolve hostname '%s': %s"),
                       host, gai_strerror (ret));
683 684 685 686 687 688 689
        return -1;
    }

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

690
        sock = socket(r->ai_family, SOCK_STREAM, r->ai_protocol);
691 692 693
        if (sock == -1) {
            saved_errno = errno;
            continue;
694
        }
695

696
        if (connect(sock, r->ai_addr, r->ai_addrlen) == -1) {
697
            saved_errno = errno;
698
            VIR_FORCE_CLOSE(sock);
699 700 701 702 703 704 705 706 707
            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);
708
        VIR_FORCE_CLOSE(sock);
709
        break;
710 711
    }

712
    freeaddrinfo(res);
713

714
    if (!priv->addrlen) {
715 716
        /* Don't raise error when unprivileged, since proxy takes over */
        if (xenHavePrivilege())
717
            virReportSystemError(saved_errno,
718 719
                                 _("unable to connect to '%s:%s'"),
                                 host, port);
720 721
        return -1;
    }
722

723
    return 0;
724 725
}

726

727 728
/**
 * xend_wait_for_devices:
P
Philipp Hahn 已提交
729
 * @xend: pointer to the Xen Daemon block
730 731 732 733 734 735 736 737
 * @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
738
xend_wait_for_devices(virConnectPtr xend, const char *name)
739 740 741 742
{
    return xend_op(xend, name, "op", "wait_for_devices", NULL);
}

743

744
/**
745
 * xenDaemonListDomainsOld:
P
Philipp Hahn 已提交
746
 * @xend: pointer to the Xen Daemon block
747 748 749 750 751 752
 *
 * 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.
 */
753
char **
754
xenDaemonListDomainsOld(virConnectPtr xend)
755 756 757 758
{
    struct sexpr *root = NULL;
    char **ret = NULL;
    int count = 0;
759
    size_t i;
760 761 762 763 764 765
    struct sexpr *_for_i, *node;

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

766 767
    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) {
768 769 770 771 772
        if (node->kind != SEXPR_VALUE)
            continue;
        count++;
    }

773
    if (VIR_ALLOC_N(ret, count + 1) < 0)
774 775 776
        goto error;

    i = 0;
777 778
    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) {
779 780
        if (node->kind != SEXPR_VALUE)
            continue;
781
        if (VIR_STRDUP(ret[i], node->u.value) < 0)
E
Eric Blake 已提交
782
            goto no_memory;
783 784 785 786 787
        i++;
    }

    ret[i] = NULL;

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

792
 no_memory:
E
Eric Blake 已提交
793 794 795 796
    for (i = 0; i < count; i++)
        VIR_FREE(ret[i]);
    VIR_FREE(ret);
    goto error;
797 798
}

799

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

int
815
xenDaemonDomainCreateXML(virConnectPtr xend, const char *sexpr)
816
{
P
Philipp Hahn 已提交
817
    int ret;
818

P
Philipp Hahn 已提交
819
    ret = xend_op(xend, "", "op", "create", "config", sexpr, NULL);
820 821 822

    return ret;
}
823

824

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

844
    if (uuid != NULL)
845
        memset(uuid, 0, VIR_UUID_BUFLEN);
846 847 848 849 850
    root = sexpr_get(xend, "/xend/domain/%s?detail=1", domname);
    if (root == NULL)
        goto error;

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

868
 error:
869
    sexpr_free(root);
870
    return ret;
871 872
}

873

874
static int
875 876
xend_detect_config_version(virConnectPtr conn)
{
877 878
    struct sexpr *root;
    const char *value;
879
    xenUnifiedPrivatePtr priv = conn->privateData;
880

881 882
    root = sexpr_get(conn, "/xend/node/");
    if (root == NULL)
883
        return -1;
884

885
    value = sexpr_node(root, "node/xend_config_format");
886

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

D
Daniel Veillard 已提交
898

899 900 901 902 903 904 905 906 907 908
/**
 * 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)
909
sexpr_to_xend_domain_state(virDomainDefPtr def, const struct sexpr *root)
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
{
    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;
927
    } else if (def->id < 0 || sexpr_int(root, "domain/status") == 0) {
928 929 930 931 932 933 934
        /* 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)
         */
935 936 937 938 939 940
        state = VIR_DOMAIN_SHUTOFF;
    }

    return state;
}

D
Daniel Veillard 已提交
941
/**
942 943 944 945 946 947 948 949 950 951
 * 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
952
sexpr_to_xend_domain_info(virDomainDefPtr def,
953
                          const struct sexpr *root,
954
                          virDomainInfoPtr info)
955
{
956
    int vcpus;
957

958
    info->state = sexpr_to_xend_domain_state(def, root);
959 960 961
    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;
962

963
    vcpus = sexpr_int(root, "domain/vcpus");
964
    info->nrVirtCpu = count_one_bits_l(sexpr_u64(root, "domain/vcpu_avail"));
965 966 967
    if (!info->nrVirtCpu || vcpus < info->nrVirtCpu)
        info->nrVirtCpu = vcpus;

968
    return 0;
969 970
}

971 972 973 974 975 976 977 978 979 980 981
/**
 * 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
982
sexpr_to_xend_node_info(const struct sexpr *root, virNodeInfoPtr info)
983 984 985 986
{
    const char *machine;

    machine = sexpr_node(root, "node/machine");
987
    if (machine == NULL) {
988
        info->model[0] = 0;
989
    } else {
990
        snprintf(&info->model[0], sizeof(info->model) - 1, "%s", machine);
991
        info->model[sizeof(info->model) - 1] = 0;
992 993 994 995 996 997 998
    }
    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");
999 1000 1001
    info->cores = sexpr_int(root, "node/cores_per_socket");
    info->threads = sexpr_int(root, "node/threads_per_core");

1002 1003 1004 1005 1006 1007 1008
    /* 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");
1009 1010
        int procs = info->nodes * info->cores * info->threads;
        if (procs == 0) /* Sanity check in case of Xen bugs in futures..*/
1011
            return -1;
1012
        info->sockets = nr_cpus / procs;
1013
    }
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027

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

1028
    return 0;
1029 1030
}

1031

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

    nodeToCpu = sexpr_node(root, "node/node_to_cpu");
1055 1056
    if (nodeToCpu == NULL)
        return 0;               /* no NUMA support */
1057 1058 1059

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

1060 1061 1062

    cur = nodeToCpu;
    while (*cur != 0) {
1063
        virBitmapPtr cpuset = NULL;
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
        /*
         * 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 已提交
1074
        virSkipSpacesAndBackslash(&cur);
1075 1076 1077
        if (*cur != ':')
            goto parse_error;
        cur++;
E
Eric Blake 已提交
1078
        virSkipSpacesAndBackslash(&cur);
1079
        if (STRPREFIX(cur, "no cpus")) {
1080
            nb_cpus = 0;
1081
            if (!(cpuset = virBitmapNew(numCpus)))
1082
                goto error;
1083
        } else {
1084
            nb_cpus = virBitmapParse(cur, 'n', &cpuset, numCpus);
1085 1086 1087 1088
            if (nb_cpus < 0)
                goto error;
        }

1089 1090
        if (VIR_ALLOC_N(cpuInfo, numCpus) < 0) {
            virBitmapFree(cpuset);
1091
            goto error;
1092
        }
1093

1094 1095 1096 1097 1098
        for (n = 0, cpu = 0; cpu < numCpus; cpu++) {
            bool used;

            ignore_value(virBitmapGetBit(cpuset, cpu, &used));
            if (used)
1099
                cpuInfo[n++].id = cpu;
1100
        }
1101
        virBitmapFree(cpuset);
1102

1103
        if (virCapabilitiesAddHostNUMACell(caps, cell, nb_cpus, 0, cpuInfo) < 0)
1104
            goto error;
1105
        cpuInfo = NULL;
1106
    }
1107

1108
    return 0;
1109

1110
 parse_error:
1111
    virReportError(VIR_ERR_XEN_CALL, "%s", _("topology syntax error"));
1112
 error:
1113 1114
    virCapabilitiesClearHostNUMACellCPUTopology(cpuInfo, nb_cpus);
    VIR_FREE(cpuInfo);
1115
    return -1;
1116 1117
}

1118

1119 1120 1121 1122 1123 1124 1125
/**
 * 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
 *
1126
 * Returns the domain def pointer or NULL in case of error.
1127
 */
1128
static virDomainDefPtr
1129
sexpr_to_domain(virConnectPtr conn, const struct sexpr *root)
1130
{
1131
    virDomainDefPtr ret = NULL;
1132
    unsigned char uuid[VIR_UUID_BUFLEN];
1133
    const char *name;
1134
    const char *tmp;
1135
    int id = -1;
1136
    xenUnifiedPrivatePtr priv = conn->privateData;
1137

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

1144 1145 1146 1147
    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
     */
1148
    if (!tmp && priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4)
1149 1150
        goto error;

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

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

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

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

/*****************************************************************
 ******
 ******
 ******
 ******
             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.
 */
1185
int
1186 1187
xenDaemonOpen(virConnectPtr conn,
              virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
1188
              unsigned int flags)
1189
{
1190
    char *port = NULL;
1191
    int ret = -1;
1192

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

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

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

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

1237
 done:
1238
    ret = 0;
1239

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

1245 1246 1247 1248 1249 1250 1251 1252 1253

/**
 * 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.
 *
1254
 * Returns 0 in case of success, -1 in case of error
1255 1256 1257 1258
 */
int
xenDaemonClose(virConnectPtr conn ATTRIBUTE_UNUSED)
{
1259
    return 0;
1260 1261 1262 1263
}

/**
 * xenDaemonDomainSuspend:
1264 1265
 * @conn: the connection object
 * @def: the domain to suspend
1266 1267 1268 1269 1270 1271 1272
 *
 * 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
1273
xenDaemonDomainSuspend(virConnectPtr conn, virDomainDefPtr def)
1274
{
1275
    if (def->id < 0) {
1276
        virReportError(VIR_ERR_OPERATION_INVALID,
1277
                       _("Domain %s isn't running."), def->name);
1278
        return -1;
1279 1280
    }

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

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

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

/**
 * xenDaemonDomainShutdown:
1307 1308
 * @conn: the connection object
 * @def: the domain to shutdown
1309 1310 1311 1312 1313 1314 1315 1316
 *
 * 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
1317
xenDaemonDomainShutdown(virConnectPtr conn, virDomainDefPtr def)
1318
{
1319
    if (def->id < 0) {
1320
        virReportError(VIR_ERR_OPERATION_INVALID,
1321
                       _("Domain %s isn't running."), def->name);
1322
        return -1;
1323 1324
    }

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

1328 1329
/**
 * xenDaemonDomainReboot:
1330 1331
 * @conn: the connection object
 * @def: the domain to reboot
1332 1333 1334 1335 1336 1337 1338 1339
 *
 * 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
1340
xenDaemonDomainReboot(virConnectPtr conn, virDomainDefPtr def)
1341
{
1342
    if (def->id < 0) {
1343
        virReportError(VIR_ERR_OPERATION_INVALID,
1344
                       _("Domain %s isn't running."), def->name);
1345
        return -1;
1346 1347
    }

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

1351
/**
1352
 * xenDaemonDomainDestroy:
1353 1354
 * @conn: the connection object
 * @def: the domain to destroy
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
 *
 * 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
1366
xenDaemonDomainDestroy(virConnectPtr conn, virDomainDefPtr def)
1367
{
1368
    if (def->id < 0) {
1369
        virReportError(VIR_ERR_OPERATION_INVALID,
1370
                       _("Domain %s isn't running."), def->name);
1371
        return -1;
1372 1373
    }

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

1377 1378 1379 1380 1381 1382 1383 1384 1385
/**
 * 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.
 */
1386
char *
1387 1388
xenDaemonDomainGetOSType(virConnectPtr conn,
                         virDomainDefPtr def)
1389 1390 1391 1392 1393
{
    char *type;
    struct sexpr *root;

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

1398 1399
    ignore_value(VIR_STRDUP(type,
                            sexpr_lookup(root, "domain/image/hvm") ? "hvm" : "linux"));
1400

1401 1402
    sexpr_free(root);

1403
    return type;
1404 1405
}

1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
/**
 * 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
1420 1421 1422
xenDaemonDomainSave(virConnectPtr conn,
                    virDomainDefPtr def,
                    const char *filename)
1423
{
1424
    if (def->id < 0) {
1425
        virReportError(VIR_ERR_OPERATION_INVALID,
1426
                       _("Domain %s isn't running."), def->name);
1427
        return -1;
1428
    }
1429 1430

    /* We can't save the state of Domain-0, that would mean stopping it too */
1431
    if (def->id == 0) {
1432 1433
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Cannot save host domain"));
1434
        return -1;
1435 1436
    }

1437
    return xend_op(conn, def->name, "op", "save", "file", filename, NULL);
1438 1439
}

D
Daniel Veillard 已提交
1440 1441
/**
 * xenDaemonDomainCoreDump:
1442 1443
 * @conn: the connection object
 * @def: domain configuration
D
Daniel Veillard 已提交
1444 1445 1446 1447 1448 1449 1450 1451 1452
 * @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.
 */
1453
int
1454 1455
xenDaemonDomainCoreDump(virConnectPtr conn,
                        virDomainDefPtr def,
1456
                        const char *filename,
E
Eric Blake 已提交
1457
                        unsigned int flags)
D
Daniel Veillard 已提交
1458
{
E
Eric Blake 已提交
1459 1460
    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH, -1);

1461
    if (def->id < 0) {
1462
        virReportError(VIR_ERR_OPERATION_INVALID,
1463
                       _("Domain %s isn't running."), def->name);
1464
        return -1;
1465 1466
    }

1467
    return xend_op(conn, def->name,
J
Jiri Denemark 已提交
1468
                   "op", "dump", "file", filename,
P
Paolo Bonzini 已提交
1469
                   "live", (flags & VIR_DUMP_LIVE ? "1" : "0"),
1470 1471
                   "crash", (flags & VIR_DUMP_CRASH ? "1" : "0"),
                   NULL);
D
Daniel Veillard 已提交
1472 1473
}

1474 1475
/**
 * xenDaemonDomainRestore:
P
Philipp Hahn 已提交
1476
 * @conn: pointer to the Xen Daemon block
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
 * @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);
}
1490

1491

1492 1493 1494 1495 1496 1497 1498 1499
/**
 * 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.
 */
1500
unsigned long long
1501
xenDaemonDomainGetMaxMemory(virConnectPtr conn, virDomainDefPtr def)
1502
{
1503
    unsigned long long ret = 0;
1504 1505 1506
    struct sexpr *root;

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

1511
    ret = sexpr_u64(root, "domain/memory") << 10;
1512 1513
    sexpr_free(root);

1514
    return ret;
1515 1516
}

1517

1518 1519 1520 1521 1522 1523 1524
/**
 * 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
1525
 * on its own.
1526 1527 1528 1529
 *
 * Returns 0 for success; -1 (with errno) on error
 */
int
1530 1531 1532
xenDaemonDomainSetMaxMemory(virConnectPtr conn,
                            virDomainDefPtr def,
                            unsigned long memory)
1533 1534
{
    char buf[1024];
1535

1536
    snprintf(buf, sizeof(buf), "%lu", VIR_DIV_UP(memory, 1024));
1537
    return xend_op(conn, def->name, "op", "maxmem_set", "memory",
1538 1539 1540
                   buf, NULL);
}

1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
/**
 * 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
1558 1559 1560
xenDaemonDomainSetMemory(virConnectPtr conn,
                         virDomainDefPtr def,
                         unsigned long memory)
1561 1562
{
    char buf[1024];
1563

1564
    snprintf(buf, sizeof(buf), "%lu", VIR_DIV_UP(memory, 1024));
1565
    return xend_op(conn, def->name, "op", "mem_target_set",
1566 1567 1568
                   "target", buf, NULL);
}

1569

1570
virDomainDefPtr
1571
xenDaemonDomainFetch(virConnectPtr conn, int domid, const char *name,
1572
                     const char *cpus)
1573 1574
{
    struct sexpr *root;
1575
    xenUnifiedPrivatePtr priv = conn->privateData;
1576
    virDomainDefPtr def = NULL;
1577 1578 1579
    int id;
    char * tty;
    int vncport;
1580

1581 1582 1583 1584
    if (name)
        root = sexpr_get(conn, "/xend/domain/%s?detail=1", name);
    else
        root = sexpr_get(conn, "/xend/domain/%d?detail=1", domid);
1585
    if (root == NULL)
1586
        return NULL;
1587

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

1604
 cleanup:
1605 1606
    sexpr_free(root);

1607
    return def;
1608 1609 1610
}


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

1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642

/**
 * 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
1643 1644 1645
xenDaemonDomainGetInfo(virConnectPtr conn,
                       virDomainDefPtr def,
                       virDomainInfoPtr info)
1646 1647 1648 1649
{
    struct sexpr *root;
    int ret;

1650
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
1651
    if (root == NULL)
1652
        return -1;
1653

1654
    ret = sexpr_to_xend_domain_info(def, root, info);
1655
    sexpr_free(root);
1656
    return ret;
1657
}
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670


/**
 * 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
1671 1672
xenDaemonDomainGetState(virConnectPtr conn,
                        virDomainDefPtr def,
1673
                        int *state,
1674
                        int *reason)
1675 1676 1677
{
    struct sexpr *root;

1678
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
1679 1680 1681
    if (!root)
        return -1;

1682
    *state = sexpr_to_xend_domain_state(def, root);
1683 1684 1685 1686 1687 1688
    if (reason)
        *reason = 0;

    sexpr_free(root);
    return 0;
}
1689

1690

1691
/**
1692
 * xenDaemonLookupByName:
1693 1694 1695 1696 1697 1698 1699
 * @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.
 *
1700
 * Returns domain def pointer on success; NULL on error
1701
 */
1702
virDomainDefPtr
1703
xenDaemonLookupByName(virConnectPtr conn, const char *domname)
1704 1705
{
    struct sexpr *root;
1706
    virDomainDefPtr ret = NULL;
1707 1708 1709 1710 1711 1712 1713

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

    ret = sexpr_to_domain(conn, root);

1714
 error:
1715
    sexpr_free(root);
1716
    return ret;
1717
}
1718

1719

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

    root = sexpr_get(conn, "/xend/node/");
    if (root == NULL)
1737
        return -1;
1738 1739 1740

    ret = sexpr_to_xend_node_info(root, info);
    sexpr_free(root);
1741
    return ret;
1742 1743
}

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

    root = sexpr_get(conn, "/xend/node/");
    if (root == NULL) {
1761
        return -1;
1762 1763
    }

1764
    ret = sexpr_to_xend_topology(root, caps);
1765
    sexpr_free(root);
1766
    return ret;
1767 1768
}

1769

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

E
Eric Blake 已提交
1790 1791 1792 1793
    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
                  VIR_DOMAIN_VCPU_CONFIG |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

1794
    if (vcpus < 1) {
1795
        virReportError(VIR_ERR_INVALID_ARG, __FUNCTION__);
1796
        return -1;
1797 1798
    }

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

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

    snprintf(buf, sizeof(buf), "%d", vcpus);
1830
    return xend_op(conn, def->name, "op", "set_vcpus", "vcpus",
1831 1832 1833
                   buf, NULL);
}

1834 1835
/**
 * xenDaemonDomainPinCpu:
1836 1837
 * @conn: the connection object
 * @minidef: minimal domain configuration
1838 1839 1840
 * @vcpu: virtual CPU number
 * @cpumap: pointer to a bit map of real CPUs (in 8-bit bytes)
 * @maplen: length of cpumap in bytes
1841
 *
1842
 * Dynamically change the real CPUs which can be allocated to a virtual CPU.
1843 1844 1845 1846 1847
 * 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
1848 1849 1850 1851
 *
 * Returns 0 for success; -1 (with errno) on error
 */
int
1852 1853
xenDaemonDomainPinVcpu(virConnectPtr conn,
                       virDomainDefPtr minidef,
1854 1855 1856
                       unsigned int vcpu,
                       unsigned char *cpumap,
                       int maplen)
1857
{
1858
    char buf[VIR_UUID_BUFLEN], mapstr[sizeof(cpumap_t) * 64];
1859 1860
    size_t i, j;
    int ret;
1861
    xenUnifiedPrivatePtr priv = conn->privateData;
1862
    virDomainDefPtr def = NULL;
1863

1864
    if (maplen > (int)sizeof(cpumap_t)) {
1865
        virReportError(VIR_ERR_INVALID_ARG, __FUNCTION__);
1866
        return -1;
1867
    }
1868

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

1876 1877 1878
    /* 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)) {
1879
        snprintf(buf, sizeof(buf), "%zu,", (8 * i) + j);
1880 1881
        strcat(mapstr, buf);
    }
1882
    if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4)
1883 1884 1885 1886
        mapstr[strlen(mapstr) - 1] = ']';
    else
        mapstr[strlen(mapstr) - 1] = 0;

1887
    snprintf(buf, sizeof(buf), "%d", vcpu);
1888

1889
    ret = xend_op(conn, minidef->name, "op", "pincpu", "vcpu", buf,
1890 1891
                  "cpumap", mapstr, NULL);

1892 1893 1894
    if (!(def = xenDaemonDomainFetch(conn,
                                     minidef->id,
                                     minidef->name,
1895 1896 1897 1898
                                     NULL)))
        goto cleanup;

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

    return ret;

1917
 cleanup:
1918 1919
    virDomainDefFree(def);
    return -1;
1920 1921
}

1922 1923
/**
 * xenDaemonDomainGetVcpusFlags:
1924 1925
 * @conn: the connection object
 * @def: domain configuration
1926 1927 1928 1929 1930
 * @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
1931
 * issued
1932 1933 1934

 */
int
1935 1936 1937
xenDaemonDomainGetVcpusFlags(virConnectPtr conn,
                             virDomainDefPtr def,
                             unsigned int flags)
1938 1939 1940 1941
{
    struct sexpr *root;
    int ret;

E
Eric Blake 已提交
1942 1943 1944 1945
    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
                  VIR_DOMAIN_VCPU_CONFIG |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

1946
    if (def->id < 0 && (flags & VIR_DOMAIN_VCPU_LIVE)) {
1947 1948
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("domain not active"));
1949 1950 1951
        return -1;
    }

1952
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
1953 1954 1955 1956 1957
    if (root == NULL)
        return -1;

    ret = sexpr_int(root, "domain/vcpus");
    if (!(flags & VIR_DOMAIN_VCPU_MAXIMUM)) {
1958
        int vcpus = count_one_bits_l(sexpr_u64(root, "domain/vcpu_avail"));
1959 1960 1961 1962
        if (vcpus)
            ret = MIN(vcpus, ret);
    }
    if (!ret)
1963
        ret = -1;
1964 1965 1966 1967
    sexpr_free(root);
    return ret;
}

1968 1969
/**
 * virDomainGetVcpus:
1970 1971
 * @conn: the connection object
 * @def: domain configuration
1972 1973
 * @info: pointer to an array of virVcpuInfo structures (OUT)
 * @maxinfo: number of structures in info array
E
Eric Blake 已提交
1974
 * @cpumaps: pointer to a bit map of real CPUs for all vcpus of this domain (in 8-bit bytes) (OUT)
D
Daniel Veillard 已提交
1975
 *	If cpumaps is NULL, then no cpumap information is returned by the API.
1976 1977 1978 1979 1980 1981
 *	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...).
1982
 *
1983
 * Extract information about virtual CPUs of domain, store it in info array
D
Daniel Veillard 已提交
1984
 * and also in cpumaps if this pointer isn't NULL.
1985 1986 1987 1988
 *
 * Returns the number of info filled in case of success, -1 in case of failure.
 */
int
1989 1990
xenDaemonDomainGetVcpus(virConnectPtr conn,
                        virDomainDefPtr def,
1991 1992 1993 1994
                        virVcpuInfoPtr info,
                        int maxinfo,
                        unsigned char *cpumaps,
                        int maplen)
1995 1996 1997 1998 1999 2000 2001
{
    struct sexpr *root, *s, *t;
    virVcpuInfoPtr ipt = info;
    int nbinfo = 0, oln;
    unsigned char *cpumap;
    int vcpu, cpu;

2002
    root = sexpr_get(conn, "/xend/domain/%s?op=vcpuinfo", def->name);
2003
    if (root == NULL)
2004
        return -1;
2005 2006

    if (cpumaps != NULL)
2007
        memset(cpumaps, 0, maxinfo * maplen);
2008 2009

    /* scan the sexprs from "(vcpu (number x)...)" and get parameter values */
2010 2011 2012
    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) &&
2013
            STREQ(s->u.s.car->u.s.car->u.value, "vcpu")) {
2014
            t = s->u.s.car;
2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030
            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
                 */
2031 2032 2033
                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) &&
2034
                        STREQ(t->u.s.car->u.s.car->u.value, "cpumap") &&
2035 2036
                        (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)
2037
                            if (t->u.s.car->kind == SEXPR_VALUE
2038
                                && virStrToLong_i(t->u.s.car->u.value, NULL, 10, &cpu) == 0
2039 2040 2041
                                && cpu >= 0
                                && (VIR_CPU_MAPLEN(cpu+1) <= maplen)) {
                                VIR_USE_CPU(cpumap, cpu);
2042 2043 2044
                            }
                        break;
                    }
2045 2046
            }

2047 2048 2049
            if (++nbinfo == maxinfo) break;
            ipt++;
        }
2050 2051
    }
    sexpr_free(root);
2052
    return nbinfo;
2053 2054
}

2055 2056 2057 2058 2059 2060 2061
/**
 * 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.
 *
2062
 * Returns domain def pointer on success; NULL on error
2063
 */
2064
virDomainDefPtr
2065 2066
xenDaemonLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
2067
    virDomainDefPtr ret;
2068 2069
    char *name = NULL;
    int id = -1;
2070
    xenUnifiedPrivatePtr priv = conn->privateData;
2071

2072
    /* Old approach for xen <= 3.0.3 */
2073
    if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4) {
2074 2075 2076 2077 2078 2079
        char **names, **tmp;
        unsigned char ident[VIR_UUID_BUFLEN];
        names = xenDaemonListDomainsOld(conn);
        tmp = names;

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

2104
        virUUIDFormat(uuid, uuidstr);
2105 2106
        root = sexpr_get(conn, "/xend/domain/%s?detail=1", uuidstr);
        if (root == NULL)
2107
            return NULL;
2108 2109 2110 2111 2112
        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;
2113

2114
        ignore_value(VIR_STRDUP(name, domname));
2115

2116
        sexpr_free(root);
2117 2118 2119
    }

    if (name == NULL)
2120
        return NULL;
2121

2122
    ret = virDomainDefNew(name, uuid, id);
2123

2124
    VIR_FREE(name);
2125
    return ret;
2126
}
2127 2128

/**
2129
 * xenDaemonCreateXML:
2130
 * @conn: pointer to the hypervisor connection
2131
 * @def: domain configuration
2132 2133 2134 2135
 * @flags: an optional set of virDomainFlags
 *
 * Launch a new Linux guest domain, based on an XML description similar
 * to the one returned by virDomainGetXMLDesc()
2136
 * This function may requires privileged access to the hypervisor.
2137
 *
2138 2139
 * Returns a new domain object or NULL in case of failure
 */
2140 2141
int
xenDaemonCreateXML(virConnectPtr conn, virDomainDefPtr def)
2142 2143 2144
{
    int ret;
    char *sexpr;
2145 2146
    const char *tmp;
    struct sexpr *root;
2147
    xenUnifiedPrivatePtr priv = conn->privateData;
2148

2149 2150 2151 2152 2153
    if (def->id != -1) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Domain %s is already running"),
                       def->name);
        return -1;
2154 2155
    }

2156 2157 2158
    if (!(sexpr = xenFormatSxpr(conn, def, priv->xendConfigVersion)))
        return -1;

2159
    ret = xenDaemonDomainCreateXML(conn, sexpr);
2160
    VIR_FREE(sexpr);
2161 2162 2163 2164
    if (ret != 0) {
        goto error;
    }

2165 2166
    /* This comes before wait_for_devices, to ensure that latter
       cleanup will destroy the domain upon failure */
2167 2168
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
    if (root == NULL)
2169 2170
        goto error;

2171 2172 2173 2174 2175 2176 2177 2178 2179 2180
    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");

2181
    if (xend_wait_for_devices(conn, def->name) < 0)
2182 2183
        goto error;

2184
    if (xenDaemonDomainResume(conn, def) < 0)
2185 2186
        goto error;

2187
    return 0;
2188

2189
 error:
2190
    /* Make sure we don't leave a still-born domain around */
2191
    if (def->id != -1)
2192
        xenDaemonDomainDestroy(conn, def);
2193
    return -1;
2194
}
2195 2196

/**
2197
 * xenDaemonAttachDeviceFlags:
2198 2199
 * @conn: the connection object
 * @minidef: domain configuration
2200
 * @xml: pointer to XML description of device
2201
 * @flags: an OR'ed set of virDomainDeviceModifyFlags
2202
 *
2203 2204 2205 2206 2207
 * 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.
 */
2208
int
2209 2210
xenDaemonAttachDeviceFlags(virConnectPtr conn,
                           virDomainDefPtr minidef,
2211
                           const char *xml,
2212
                           unsigned int flags)
2213
{
2214
    xenUnifiedPrivatePtr priv = conn->privateData;
2215 2216 2217 2218 2219
    char *sexpr = NULL;
    int ret = -1;
    virDomainDeviceDefPtr dev = NULL;
    virDomainDefPtr def = NULL;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
2220
    char class[8], ref[80];
2221
    char *target = NULL;
2222

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

2225
    if (minidef->id < 0) {
2226 2227
        /* Cannot modify live config if domain is inactive */
        if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
2228 2229
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Cannot modify live config if domain is inactive"));
2230 2231
            return -1;
        }
2232 2233
    } else {
        /* Only live config can be changed if xendConfigVersion < 3 */
2234
        if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4 &&
E
Eric Blake 已提交
2235
            (flags != VIR_DOMAIN_DEVICE_MODIFY_CURRENT &&
2236
             flags != VIR_DOMAIN_DEVICE_MODIFY_LIVE)) {
2237 2238 2239
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Xend version does not support modifying "
                             "persistent config"));
2240 2241
            return -1;
        }
2242
        /* Xen only supports modifying both live and persistent config if
2243 2244
         * xendConfigVersion >= 3
         */
2245
        if (priv->xendConfigVersion >= XEND_CONFIG_VERSION_3_0_4 &&
2246 2247
            (flags != (VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                       VIR_DOMAIN_DEVICE_MODIFY_CONFIG))) {
2248 2249 2250
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Xend only supports modifying both live and "
                             "persistent config"));
2251 2252 2253
            return -1;
        }
    }
2254

2255 2256 2257
    if (!(def = xenDaemonDomainFetch(conn,
                                     minidef->id,
                                     minidef->name,
2258 2259 2260
                                     NULL)))
        goto cleanup;

2261 2262
    if (!(dev = virDomainDeviceDefParse(xml, def, priv->caps, priv->xmlopt,
                                        VIR_DOMAIN_XML_INACTIVE)))
2263 2264 2265 2266 2267
        goto cleanup;


    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
2268 2269 2270 2271
        if (xenFormatSxprDisk(dev->data.disk,
                              &buf,
                              STREQ(def->os.type, "hvm") ? 1 : 0,
                              priv->xendConfigVersion, 1) < 0)
2272
            goto cleanup;
2273

2274 2275 2276
        if (dev->data.disk->device != VIR_DOMAIN_DISK_DEVICE_CDROM &&
            VIR_STRDUP(target, dev->data.disk->dst) < 0)
            goto cleanup;
2277
        break;
2278 2279

    case VIR_DOMAIN_DEVICE_NET:
2280
        if (xenFormatSxprNet(conn,
M
Markus Groß 已提交
2281 2282 2283 2284
                             dev->data.net,
                             &buf,
                             STREQ(def->os.type, "hvm") ? 1 : 0,
                             priv->xendConfigVersion, 1) < 0)
2285
            goto cleanup;
2286 2287

        char macStr[VIR_MAC_STRING_BUFLEN];
2288
        virMacAddrFormat(&dev->data.net->mac, macStr);
2289

2290
        if (VIR_STRDUP(target, macStr) < 0)
2291
            goto cleanup;
2292
        break;
2293

2294 2295 2296
    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ß 已提交
2297
            if (xenFormatSxprOnePCI(dev->data.hostdev, &buf, 0) < 0)
2298
                goto cleanup;
2299

2300
            virDevicePCIAddress PCIAddr;
2301

2302
            PCIAddr = dev->data.hostdev->source.subsys.u.pci.addr;
2303
            if (virAsprintf(&target, "PCI device: %.4x:%.2x:%.2x",
2304
                            PCIAddr.domain, PCIAddr.bus, PCIAddr.slot) < 0)
2305
                goto cleanup;
2306
        } else {
2307 2308
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("unsupported device type"));
2309 2310 2311 2312
            goto cleanup;
        }
        break;

2313
    default:
2314 2315
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("unsupported device type"));
2316
        goto cleanup;
2317
    }
2318 2319 2320

    sexpr = virBufferContentAndReset(&buf);

2321
    if (virDomainXMLDevID(conn, minidef, dev, class, ref, sizeof(ref))) {
2322
        /* device doesn't exist, define it */
2323
        ret = xend_op(conn, def->name, "op", "device_create",
2324
                      "config", sexpr, NULL);
2325 2326
    } else {
        if (dev->data.disk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
2327 2328
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("target '%s' already exists"), target);
2329 2330
        } else {
            /* device exists, attempt to modify it */
2331
            ret = xend_op(conn, minidef->name, "op", "device_configure",
2332 2333
                          "config", sexpr, "dev", ref, NULL);
        }
2334
    }
2335

2336
 cleanup:
2337
    VIR_FREE(sexpr);
2338 2339
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);
2340
    VIR_FREE(target);
2341 2342 2343
    return ret;
}

2344 2345
/**
 * xenDaemonUpdateDeviceFlags:
2346 2347
 * @conn: the connection object
 * @minidef: domain configuration
2348 2349 2350 2351 2352 2353 2354 2355
 * @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.
 */
2356
int
2357 2358
xenDaemonUpdateDeviceFlags(virConnectPtr conn,
                           virDomainDefPtr minidef,
2359
                           const char *xml,
2360 2361
                           unsigned int flags)
{
2362
    xenUnifiedPrivatePtr priv = conn->privateData;
2363 2364 2365 2366 2367 2368 2369
    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 已提交
2370
    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_LIVE |
2371 2372
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG, -1);

2373
    if (minidef->id < 0) {
2374 2375
        /* Cannot modify live config if domain is inactive */
        if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
2376 2377
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Cannot modify live config if domain is inactive"));
2378 2379
            return -1;
        }
2380 2381
    } else {
        /* Only live config can be changed if xendConfigVersion < 3 */
2382
        if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4 &&
E
Eric Blake 已提交
2383
            (flags != VIR_DOMAIN_DEVICE_MODIFY_CURRENT &&
2384
             flags != VIR_DOMAIN_DEVICE_MODIFY_LIVE)) {
2385 2386 2387
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Xend version does not support modifying "
                             "persistent config"));
2388 2389 2390 2391 2392
            return -1;
        }
        /* Xen only supports modifying both live and persistent config if
         * xendConfigVersion >= 3
         */
2393
        if (priv->xendConfigVersion >= XEND_CONFIG_VERSION_3_0_4 &&
2394 2395
            (flags != (VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                       VIR_DOMAIN_DEVICE_MODIFY_CONFIG))) {
2396 2397 2398
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Xend only supports modifying both live and "
                             "persistent config"));
2399 2400 2401 2402
            return -1;
        }
    }

2403 2404 2405
    if (!(def = xenDaemonDomainFetch(conn,
                                     minidef->id,
                                     minidef->name,
2406 2407 2408
                                     NULL)))
        goto cleanup;

2409 2410
    if (!(dev = virDomainDeviceDefParse(xml, def, priv->caps, priv->xmlopt,
                                        VIR_DOMAIN_XML_INACTIVE)))
2411 2412 2413 2414 2415
        goto cleanup;


    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
2416
        if (xenFormatSxprDisk(dev->data.disk,
M
Markus Groß 已提交
2417 2418 2419
                              &buf,
                              STREQ(def->os.type, "hvm") ? 1 : 0,
                              priv->xendConfigVersion, 1) < 0)
2420 2421 2422 2423
            goto cleanup;
        break;

    default:
2424 2425
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("unsupported device type"));
2426 2427 2428 2429 2430
        goto cleanup;
    }

    sexpr = virBufferContentAndReset(&buf);

2431
    if (virDomainXMLDevID(conn, minidef, dev, class, ref, sizeof(ref))) {
2432 2433
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("requested device does not exist"));
2434 2435 2436
        goto cleanup;
    } else {
        /* device exists, attempt to modify it */
2437
        ret = xend_op(conn, minidef->name, "op", "device_configure",
2438 2439 2440
                      "config", sexpr, "dev", ref, NULL);
    }

2441
 cleanup:
2442 2443 2444 2445 2446 2447
    VIR_FREE(sexpr);
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);
    return ret;
}

2448
/**
2449
 * xenDaemonDetachDeviceFlags:
2450 2451
 * @conn: the connection object
 * @minidef: domain configuration
2452
 * @xml: pointer to XML description of device
2453
 * @flags: an OR'ed set of virDomainDeviceModifyFlags
2454
 *
2455 2456 2457 2458
 * Destroy a virtual device attachment to backend.
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
2459
int
2460 2461
xenDaemonDetachDeviceFlags(virConnectPtr conn,
                           virDomainDefPtr minidef,
2462
                           const char *xml,
2463
                           unsigned int flags)
2464
{
2465
    xenUnifiedPrivatePtr priv = conn->privateData;
2466
    char class[8], ref[80];
2467 2468 2469
    virDomainDeviceDefPtr dev = NULL;
    virDomainDefPtr def = NULL;
    int ret = -1;
2470 2471
    char *xendev = NULL;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
2472

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

2475
    if (minidef->id < 0) {
2476 2477
        /* Cannot modify live config if domain is inactive */
        if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
2478 2479
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Cannot modify live config if domain is inactive"));
2480 2481
            return -1;
        }
2482 2483
    } else {
        /* Only live config can be changed if xendConfigVersion < 3 */
2484
        if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4 &&
E
Eric Blake 已提交
2485
            (flags != VIR_DOMAIN_DEVICE_MODIFY_CURRENT &&
2486
             flags != VIR_DOMAIN_DEVICE_MODIFY_LIVE)) {
2487 2488 2489
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Xend version does not support modifying "
                             "persistent config"));
2490 2491
            return -1;
        }
2492
        /* Xen only supports modifying both live and persistent config if
2493 2494
         * xendConfigVersion >= 3
         */
2495
        if (priv->xendConfigVersion >= XEND_CONFIG_VERSION_3_0_4 &&
2496 2497
            (flags != (VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                       VIR_DOMAIN_DEVICE_MODIFY_CONFIG))) {
2498 2499 2500
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Xend only supports modifying both live and "
                             "persistent config"));
2501 2502 2503
            return -1;
        }
    }
2504

2505 2506 2507
    if (!(def = xenDaemonDomainFetch(conn,
                                     minidef->id,
                                     minidef->name,
2508 2509 2510
                                     NULL)))
        goto cleanup;

2511 2512
    if (!(dev = virDomainDeviceDefParse(xml, def, priv->caps, priv->xmlopt,
                                        VIR_DOMAIN_XML_INACTIVE)))
2513 2514
        goto cleanup;

2515
    if (virDomainXMLDevID(conn, minidef, dev, class, ref, sizeof(ref)))
2516 2517
        goto cleanup;

2518 2519 2520
    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ß 已提交
2521
            if (xenFormatSxprOnePCI(dev->data.hostdev, &buf, 1) < 0)
2522 2523
                goto cleanup;
        } else {
2524 2525
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("unsupported device type"));
2526 2527 2528
            goto cleanup;
        }
        xendev = virBufferContentAndReset(&buf);
2529
        ret = xend_op(conn, minidef->name, "op", "device_configure",
2530 2531 2532 2533
                      "config", xendev, "dev", ref, NULL);
        VIR_FREE(xendev);
    }
    else {
2534
        ret = xend_op(conn, minidef->name, "op", "device_destroy",
2535 2536 2537
                      "type", class, "dev", ref, "force", "0", "rm_cfg", "1",
                      NULL);
    }
2538

2539
 cleanup:
2540 2541 2542 2543
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);

    return ret;
2544
}
2545

2546
int
2547 2548 2549
xenDaemonDomainGetAutostart(virConnectPtr conn,
                            virDomainDefPtr def,
                            int *autostart)
2550 2551 2552 2553
{
    struct sexpr *root;
    const char *tmp;

2554
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
2555
    if (root == NULL) {
2556 2557
        virReportError(VIR_ERR_XEN_CALL,
                       "%s", _("xenDaemonGetAutostart failed to find this domain"));
2558
        return -1;
2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572
    }

    *autostart = 0;

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

    sexpr_free(root);
    return 0;
}

int
2573 2574 2575
xenDaemonDomainSetAutostart(virConnectPtr conn,
                            virDomainDefPtr def,
                            int autostart)
2576 2577
{
    struct sexpr *root, *autonode;
2578 2579
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    char *content = NULL;
2580 2581
    int ret = -1;

2582
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
2583
    if (root == NULL) {
2584 2585
        virReportError(VIR_ERR_XEN_CALL,
                       "%s", _("xenDaemonSetAutostart failed to find this domain"));
2586
        return -1;
2587 2588
    }

2589 2590 2591 2592
    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);
2593
        if (!val || (!STREQ(val, "ignore") && !STREQ(val, "start"))) {
2594 2595
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("unexpected value from on_xend_start"));
2596 2597 2598
            goto error;
        }

2599
        /* Change the autostart value in place, then define the new sexpr */
2600
        VIR_FREE(autonode->u.s.car->u.value);
2601 2602
        if (VIR_STRDUP(autonode->u.s.car->u.value,
                       autostart ? "start" : "ignore") < 0)
2603 2604
            goto error;

2605
        if (sexpr2string(root, &buffer) < 0) {
2606 2607
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("sexpr2string failed"));
2608 2609
            goto error;
        }
2610 2611 2612 2613 2614 2615 2616 2617

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

        content = virBufferContentAndReset(&buffer);

2618
        if (xend_op(conn, "", "op", "new", "config", content, NULL) != 0) {
2619 2620
            virReportError(VIR_ERR_XEN_CALL,
                           "%s", _("Failed to redefine sexpr"));
2621 2622 2623
            goto error;
        }
    } else {
2624 2625
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("on_xend_start not present in sexpr"));
2626 2627 2628 2629
        goto error;
    }

    ret = 0;
2630
 error:
2631 2632
    virBufferFreeAndReset(&buffer);
    VIR_FREE(content);
2633 2634 2635
    sexpr_free(root);
    return ret;
}
2636

2637
int
2638
xenDaemonDomainMigratePrepare(virConnectPtr dconn ATTRIBUTE_UNUSED,
2639 2640 2641 2642 2643 2644 2645
                              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)
2646
{
E
Eric Blake 已提交
2647 2648
    virCheckFlags(XEN_MIGRATION_FLAGS, -1);

2649 2650 2651 2652 2653
    /* 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) {
2654
        *uri_out = virGetHostname();
2655
        if (*uri_out == NULL)
2656 2657 2658 2659 2660 2661 2662
            return -1;
    }

    return 0;
}

int
2663 2664
xenDaemonDomainMigratePerform(virConnectPtr conn,
                              virDomainDefPtr def,
2665 2666 2667 2668 2669 2670
                              const char *cookie ATTRIBUTE_UNUSED,
                              int cookielen ATTRIBUTE_UNUSED,
                              const char *uri,
                              unsigned long flags,
                              const char *dname,
                              unsigned long bandwidth)
2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681
{
    /* 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;

2682 2683
    int undefined_source = 0;

E
Eric Blake 已提交
2684 2685
    virCheckFlags(XEN_MIGRATION_FLAGS, -1);

2686 2687
    /* Xen doesn't support renaming domains during migration. */
    if (dname) {
2688 2689 2690
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("xenDaemonDomainMigrate: Xen does not support"
                               " renaming domains during migration"));
2691 2692 2693 2694 2695 2696 2697
        return -1;
    }

    /* Xen (at least up to 3.1.0) takes a resource parameter but
     * ignores it.
     */
    if (bandwidth) {
2698 2699 2700
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("xenDaemonDomainMigrate: Xen does not support"
                               " bandwidth limits during migration"));
2701 2702 2703
        return -1;
    }

2704 2705 2706
    /*
     * Check the flags.
     */
2707
    if ((flags & VIR_MIGRATE_LIVE)) {
2708
        strcpy(live, "1");
2709 2710
        flags &= ~VIR_MIGRATE_LIVE;
    }
2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721

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

2722 2723 2724 2725
    /* This is buggy in Xend, but could be supported in principle.  Give
     * a nice error message.
     */
    if (flags & VIR_MIGRATE_PAUSED) {
2726 2727
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("xenDaemonDomainMigrate: xend cannot migrate paused domains"));
2728 2729 2730
        return -1;
    }

2731 2732
    /* XXX we could easily do tunnelled & peer2peer migration too
       if we want to. support these... */
2733
    if (flags != 0) {
2734 2735
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("xenDaemonDomainMigrate: unsupported flag"));
2736 2737 2738 2739 2740 2741 2742 2743
        return -1;
    }

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

2749
        if (uriptr->scheme && STRCASENEQ(uriptr->scheme, "xenmigr")) {
2750 2751 2752
            virReportError(VIR_ERR_INVALID_ARG,
                           "%s", _("xenDaemonDomainMigrate: only xenmigr://"
                                   " migrations are supported by Xen"));
2753
            virURIFree(uriptr);
2754 2755 2756
            return -1;
        }
        if (!uriptr->server) {
2757 2758 2759
            virReportError(VIR_ERR_INVALID_ARG,
                           "%s", _("xenDaemonDomainMigrate: a hostname must be"
                                   " specified in the URI"));
2760
            virURIFree(uriptr);
2761 2762
            return -1;
        }
2763
        if (VIR_STRDUP(hostname, uriptr->server) < 0) {
2764
            virURIFree(uriptr);
2765 2766 2767
            return -1;
        }
        if (uriptr->port)
2768 2769
            snprintf(port, sizeof(port), "%d", uriptr->port);
        virURIFree(uriptr);
2770
    }
2771
    else if ((p = strrchr(uri, ':')) != NULL) { /* "hostname:port" */
2772 2773
        int port_nr, n;

2774
        if (virStrToLong_i(p+1, NULL, 10, &port_nr) < 0) {
2775 2776
            virReportError(VIR_ERR_INVALID_ARG,
                           "%s", _("xenDaemonDomainMigrate: invalid port number"));
2777 2778
            return -1;
        }
2779
        snprintf(port, sizeof(port), "%d", port_nr);
2780 2781 2782

        /* Get the hostname. */
        n = p - uri; /* n = Length of hostname in bytes. */
2783
        if (VIR_STRDUP(hostname, uri) < 0)
2784 2785 2786 2787
            return -1;
        hostname[n] = '\0';
    }
    else {                      /* "hostname" (or IP address) */
2788
        if (VIR_STRDUP(hostname, uri) < 0)
2789 2790 2791
            return -1;
    }

2792
    VIR_DEBUG("hostname = %s, port = %s", hostname, port);
2793

J
Jim Fehlig 已提交
2794 2795 2796 2797 2798 2799
    /* 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.
     */
2800
    ret = xend_op(conn, def->name,
2801 2802 2803 2804 2805 2806 2807 2808 2809 2810
                  "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);
2811

2812
    if (ret == 0 && undefined_source)
2813
        xenDaemonDomainUndefine(conn, def);
2814

2815
    VIR_DEBUG("migration done");
2816 2817 2818 2819

    return ret;
}

2820 2821
int
xenDaemonDomainDefineXML(virConnectPtr conn, virDomainDefPtr def)
2822
{
2823
    int ret = -1;
2824
    char *sexpr;
2825
    xenUnifiedPrivatePtr priv = conn->privateData;
2826

M
Markus Groß 已提交
2827
    if (!(sexpr = xenFormatSxpr(conn, def, priv->xendConfigVersion))) {
2828 2829
        virReportError(VIR_ERR_XML_ERROR,
                       "%s", _("failed to build sexpr"));
2830
        goto cleanup;
2831 2832
    }

2833
    ret = xend_op(conn, "", "op", "new", "config", sexpr, NULL);
2834
    VIR_FREE(sexpr);
2835
    if (ret != 0) {
2836 2837
        virReportError(VIR_ERR_XEN_CALL,
                       _("Failed to create inactive domain %s"), def->name);
2838
        goto cleanup;
2839 2840
    }

2841
    ret = 0;
2842

2843
 cleanup:
2844
    return ret;
2845
}
2846

2847
int
2848 2849
xenDaemonDomainCreate(virConnectPtr conn,
                      virDomainDefPtr def)
2850
{
2851
    int ret;
2852

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

2855
    if (ret == 0) {
2856 2857
        int id = xenDaemonDomainLookupByName_ids(conn, def->name,
                                                 def->uuid);
2858
        if (id > 0)
2859
            def->id = id;
2860
    }
2861

2862
    return ret;
2863 2864
}

2865
int
2866
xenDaemonDomainUndefine(virConnectPtr conn, virDomainDefPtr def)
2867
{
2868
    return xend_op(conn, def->name, "op", "delete", NULL);
2869 2870 2871 2872 2873 2874 2875 2876 2877 2878
}

/**
 * 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
 */
2879
int
2880 2881 2882 2883 2884
xenDaemonNumOfDefinedDomains(virConnectPtr conn)
{
    struct sexpr *root = NULL;
    int ret = -1;
    struct sexpr *_for_i, *node;
2885

2886 2887 2888 2889 2890 2891
    root = sexpr_get(conn, "/xend/domain?state=halted");
    if (root == NULL)
        goto error;

    ret = 0;

2892
    /* coverity[copy_paste_error] */
2893 2894
    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) {
2895 2896 2897 2898 2899
        if (node->kind != SEXPR_VALUE)
            continue;
        ret++;
    }

2900
 error:
2901
    sexpr_free(root);
2902
    return ret;
2903 2904
}

2905
int
2906 2907 2908 2909
xenDaemonListDefinedDomains(virConnectPtr conn,
                            char **const names,
                            int maxnames)
{
2910
    struct sexpr *root = NULL;
2911
    size_t i;
2912
    int ret = 0;
2913
    struct sexpr *_for_i, *node;
2914

2915
    if (maxnames == 0)
2916
        return 0;
2917

2918 2919 2920 2921
    root = sexpr_get(conn, "/xend/domain?state=halted");
    if (root == NULL)
        goto error;

2922
    /* coverity[copy_paste_error] */
2923 2924
    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) {
2925 2926 2927
        if (node->kind != SEXPR_VALUE)
            continue;

2928
        if (VIR_STRDUP(names[ret++], node->u.value) < 0)
2929 2930
            goto error;

2931 2932 2933 2934
        if (ret >= maxnames)
            break;
    }

2935
 cleanup:
2936
    sexpr_free(root);
2937
    return ret;
2938

2939
 error:
2940
    for (i = 0; i < ret; ++i)
2941 2942
        VIR_FREE(names[i]);

2943
    ret = -1;
2944
    goto cleanup;
2945 2946
}

2947 2948
/**
 * xenDaemonGetSchedulerType:
2949
 * @conn: the hypervisor connection
2950 2951 2952 2953 2954 2955 2956
 * @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
 */
2957
char *
2958 2959
xenDaemonGetSchedulerType(virConnectPtr conn,
                          int *nparams)
2960
{
2961
    xenUnifiedPrivatePtr priv = conn->privateData;
2962 2963 2964 2965 2966
    struct sexpr *root;
    const char *ret = NULL;
    char *schedulertype = NULL;

    /* Support only xendConfigVersion >=4 */
2967
    if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_1_0) {
2968 2969
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("unsupported in xendConfigVersion < 4"));
2970 2971 2972
        return NULL;
    }

2973
    root = sexpr_get(conn, "/xend/node/");
2974 2975 2976 2977 2978 2979
    if (root == NULL)
        return NULL;

    /* get xen_scheduler from xend/node */
    ret = sexpr_node(root, "node/xen_scheduler");
    if (ret == NULL){
2980 2981
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("node information incomplete, missing scheduler name"));
2982 2983
        goto error;
    }
2984
    if (STREQ(ret, "credit")) {
2985
        if (VIR_STRDUP(schedulertype, "credit") < 0)
2986
            goto error;
2987 2988
        if (nparams)
            *nparams = XEN_SCHED_CRED_NPARAM;
2989
    } else if (STREQ(ret, "sedf")) {
2990
        if (VIR_STRDUP(schedulertype, "sedf") < 0)
2991
            goto error;
2992 2993
        if (nparams)
            *nparams = XEN_SCHED_SEDF_NPARAM;
2994
    } else {
2995
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Unknown scheduler"));
2996 2997 2998
        goto error;
    }

2999
 error:
3000 3001 3002 3003 3004 3005 3006
    sexpr_free(root);
    return schedulertype;

}

/**
 * xenDaemonGetSchedulerParameters:
3007 3008
 * @conn: the hypervisor connection
 * @def: domain configuration
3009 3010 3011 3012 3013 3014 3015 3016 3017
 * @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
 */
3018
int
3019 3020
xenDaemonGetSchedulerParameters(virConnectPtr conn,
                                virDomainDefPtr def,
3021 3022
                                virTypedParameterPtr params,
                                int *nparams)
3023
{
3024
    xenUnifiedPrivatePtr priv = conn->privateData;
3025 3026 3027 3028 3029 3030
    struct sexpr *root;
    char *sched_type = NULL;
    int sched_nparam = 0;
    int ret = -1;

    /* Support only xendConfigVersion >=4 */
3031
    if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_1_0) {
3032 3033
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("unsupported in xendConfigVersion < 4"));
3034
        return -1;
3035 3036 3037
    }

    /* look up the information by domain name */
3038
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
3039
    if (root == NULL)
3040
        return -1;
3041 3042

    /* get the scheduler type */
3043
    sched_type = xenDaemonGetSchedulerType(conn, &sched_nparam);
3044
    if (sched_type == NULL) {
3045 3046
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("Failed to get a scheduler name"));
3047 3048 3049 3050 3051
        goto error;
    }

    switch (sched_nparam){
        case XEN_SCHED_SEDF_NPARAM:
3052
            if (*nparams < XEN_SCHED_SEDF_NPARAM) {
3053 3054
                virReportError(VIR_ERR_INVALID_ARG,
                               "%s", _("Invalid parameter count"));
3055 3056 3057
                goto error;
            }

3058 3059 3060 3061 3062 3063
            /* 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) {
3064 3065
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               "%s", _("domain information incomplete, missing cpu_weight"));
3066 3067 3068
                goto error;
            }
            if (sexpr_node(root, "domain/cpu_cap") == NULL) {
3069 3070
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               "%s", _("domain information incomplete, missing cpu_cap"));
3071 3072 3073
                goto error;
            }

3074 3075
            if (virStrcpyStatic(params[0].field,
                                VIR_DOMAIN_SCHEDULER_WEIGHT) == NULL) {
3076 3077 3078
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Weight %s too big for destination"),
                               VIR_DOMAIN_SCHEDULER_WEIGHT);
C
Chris Lalancette 已提交
3079 3080
                goto error;
            }
3081
            params[0].type = VIR_TYPED_PARAM_UINT;
3082 3083
            params[0].value.ui = sexpr_int(root, "domain/cpu_weight");

3084 3085 3086
            if (*nparams > 1) {
                if (virStrcpyStatic(params[1].field,
                                    VIR_DOMAIN_SCHEDULER_CAP) == NULL) {
3087 3088 3089
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Cap %s too big for destination"),
                                   VIR_DOMAIN_SCHEDULER_CAP);
3090 3091 3092 3093
                    goto error;
                }
                params[1].type = VIR_TYPED_PARAM_UINT;
                params[1].value.ui = sexpr_int(root, "domain/cpu_cap");
C
Chris Lalancette 已提交
3094
            }
3095 3096 3097

            if (*nparams > XEN_SCHED_CRED_NPARAM)
                *nparams = XEN_SCHED_CRED_NPARAM;
3098 3099 3100
            ret = 0;
            break;
        default:
3101
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Unknown scheduler"));
3102 3103 3104
            goto error;
    }

3105
 error:
3106
    sexpr_free(root);
3107
    VIR_FREE(sched_type);
3108
    return ret;
3109 3110 3111 3112
}

/**
 * xenDaemonSetSchedulerParameters:
3113 3114
 * @conn: the hypervisor connection
 * @def: domain configuration
3115 3116 3117 3118 3119 3120 3121
 * @params: pointer to scheduler parameters
 * @nparams: a number of scheduler setting parameters
 *
 * Set the scheduler parameters
 *
 * Returns 0 or -1 in case of failure
 */
3122
int
3123 3124
xenDaemonSetSchedulerParameters(virConnectPtr conn,
                                virDomainDefPtr def,
3125 3126
                                virTypedParameterPtr params,
                                int nparams)
3127
{
3128
    xenUnifiedPrivatePtr priv = conn->privateData;
3129 3130
    struct sexpr *root;
    char *sched_type = NULL;
3131
    size_t i;
3132 3133 3134 3135
    int sched_nparam = 0;
    int ret = -1;

    /* Support only xendConfigVersion >=4 and active domains */
3136
    if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_1_0) {
3137 3138
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("unsupported in xendConfigVersion < 4"));
3139
        return -1;
3140 3141 3142
    }

    /* look up the information by domain name */
3143
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
3144
    if (root == NULL)
3145
        return -1;
3146 3147

    /* get the scheduler type */
3148
    sched_type = xenDaemonGetSchedulerType(conn, &sched_nparam);
3149
    if (sched_type == NULL) {
3150 3151
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("Failed to get a scheduler name"));
3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169
        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++) {
3170
                if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_WEIGHT) &&
3171
                    params[i].type == VIR_TYPED_PARAM_UINT) {
3172
                    snprintf(buf_weight, sizeof(buf_weight), "%u", params[i].value.ui);
3173
                } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_CAP) &&
3174
                    params[i].type == VIR_TYPED_PARAM_UINT) {
3175 3176
                    snprintf(buf_cap, sizeof(buf_cap), "%u", params[i].value.ui);
                } else {
3177
                    virReportError(VIR_ERR_INVALID_ARG, __FUNCTION__);
3178 3179 3180 3181 3182 3183 3184 3185
                    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) {
3186 3187
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("domain information incomplete, missing cpu_weight"));
3188 3189 3190 3191 3192 3193 3194
                    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) {
3195 3196
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("domain information incomplete, missing cpu_cap"));
3197 3198 3199 3200 3201
                    goto error;
                }
                snprintf(buf_cap, sizeof(buf_cap), "%s", cap);
            }

3202
            ret = xend_op(conn, def->name, "op",
3203 3204 3205 3206 3207
                          "domain_sched_credit_set", "weight", buf_weight,
                          "cap", buf_cap, NULL);
            break;
        }
        default:
3208
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Unknown scheduler"));
3209 3210 3211
            goto error;
    }

3212
 error:
3213
    sexpr_free(root);
3214
    VIR_FREE(sched_type);
3215
    return ret;
3216 3217
}

R
Richard W.M. Jones 已提交
3218 3219
/**
 * xenDaemonDomainBlockPeek:
3220 3221
 * @conn: the hypervisor connection
 * @minidef: minimal domain configuration
R
Richard W.M. Jones 已提交
3222 3223 3224 3225 3226
 * @path: path to the file or device
 * @offset: offset
 * @size: size
 * @buffer: return buffer
 *
3227
 * Returns 0 if successful, -1 if error
R
Richard W.M. Jones 已提交
3228 3229
 */
int
3230 3231
xenDaemonDomainBlockPeek(virConnectPtr conn,
                         virDomainDefPtr minidef,
3232 3233 3234
                         const char *path,
                         unsigned long long offset,
                         size_t size,
3235
                         void *buffer)
R
Richard W.M. Jones 已提交
3236
{
3237
    xenUnifiedPrivatePtr priv = conn->privateData;
3238 3239
    struct sexpr *root = NULL;
    int fd = -1, ret = -1;
3240
    virDomainDefPtr def = NULL;
3241 3242 3243
    int id;
    char * tty;
    int vncport;
3244
    const char *actual;
R
Richard W.M. Jones 已提交
3245 3246

    /* Security check: The path must correspond to a block device. */
3247 3248 3249 3250 3251 3252
    if (minidef->id > 0)
        root = sexpr_get(conn, "/xend/domain/%d?detail=1",
                         minidef->id);
    else if (minidef->id < 0)
        root = sexpr_get(conn, "/xend/domain/%s?detail=1",
                         minidef->name);
R
Richard W.M. Jones 已提交
3253 3254
    else {
        /* This call always fails for dom0. */
3255 3256
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domainBlockPeek is not supported for dom0"));
R
Richard W.M. Jones 已提交
3257 3258 3259 3260
        return -1;
    }

    if (!root) {
3261
        virReportError(VIR_ERR_XEN_CALL, __FUNCTION__);
R
Richard W.M. Jones 已提交
3262 3263 3264
        return -1;
    }

3265 3266
    if (xenGetDomIdFromSxpr(root, priv->xendConfigVersion, &id) < 0)
        goto cleanup;
3267
    xenUnifiedLock(priv);
3268 3269
    tty = xenStoreDomainGetConsolePath(conn, id);
    vncport = xenStoreDomainGetVNCPort(conn, id);
3270 3271
    xenUnifiedUnlock(priv);

M
Markus Groß 已提交
3272 3273
    if (!(def = xenParseSxpr(root, priv->xendConfigVersion, NULL, tty,
                             vncport)))
3274
        goto cleanup;
R
Richard W.M. Jones 已提交
3275

3276
    if (!(actual = virDomainDiskPathByName(def, path))) {
3277 3278
        virReportError(VIR_ERR_INVALID_ARG,
                       _("%s: invalid path"), path);
3279
        goto cleanup;
R
Richard W.M. Jones 已提交
3280
    }
3281
    path = actual;
R
Richard W.M. Jones 已提交
3282 3283

    /* The path is correct, now try to open it and get its size. */
3284
    fd = open(path, O_RDONLY);
3285
    if (fd == -1) {
3286
        virReportSystemError(errno,
3287 3288
                             _("failed to open for reading: %s"),
                             path);
3289
        goto cleanup;
R
Richard W.M. Jones 已提交
3290 3291 3292 3293 3294 3295
    }

    /* Seek and read. */
    /* NB. Because we configure with AC_SYS_LARGEFILE, off_t should
     * be 64 bits on all platforms.
     */
3296 3297
    if (lseek(fd, offset, SEEK_SET) == (off_t) -1 ||
        saferead(fd, buffer, size) == (ssize_t) -1) {
3298
        virReportSystemError(errno,
3299 3300
                             _("failed to lseek or read from file: %s"),
                             path);
3301
        goto cleanup;
R
Richard W.M. Jones 已提交
3302 3303 3304
    }

    ret = 0;
3305
 cleanup:
3306
    VIR_FORCE_CLOSE(fd);
3307 3308
    sexpr_free(root);
    virDomainDefFree(def);
R
Richard W.M. Jones 已提交
3309 3310 3311
    return ret;
}

3312 3313 3314

/**
 * virDomainXMLDevID:
3315 3316
 * @conn: the hypervisor connection
 * @minidef: minimal domain configuration
3317 3318 3319 3320 3321 3322 3323 3324
 * @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.
3325 3326
 *  - if pci, get BDF from description, scan XenStore and
 *    copy in ref the corresponding dev number.
3327 3328 3329 3330
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
static int
3331 3332
virDomainXMLDevID(virConnectPtr conn,
                  virDomainDefPtr def,
3333 3334 3335 3336 3337
                  virDomainDeviceDefPtr dev,
                  char *class,
                  char *ref,
                  int ref_len)
{
3338
    xenUnifiedPrivatePtr priv = conn->privateData;
3339
    char *xref;
C
Chris Lalancette 已提交
3340
    char *tmp;
3341
    const char *driver = virDomainDiskGetDriver(dev->data.disk);
3342 3343

    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
3344 3345
        if (STREQ_NULLABLE(driver, "tap") || STREQ_NULLABLE(driver, "tap2"))
            strcpy(class, driver);
3346 3347 3348
        else
            strcpy(class, "vbd");

3349 3350
        if (dev->data.disk->dst == NULL)
            return -1;
D
Daniel P. Berrange 已提交
3351
        xenUnifiedLock(priv);
3352
        xref = xenStoreDomainGetDiskID(conn, def->id,
3353
                                       dev->data.disk->dst);
D
Daniel P. Berrange 已提交
3354
        xenUnifiedUnlock(priv);
3355 3356 3357
        if (xref == NULL)
            return -1;

C
Chris Lalancette 已提交
3358
        tmp = virStrcpy(ref, xref, ref_len);
3359
        VIR_FREE(xref);
C
Chris Lalancette 已提交
3360 3361
        if (tmp == NULL)
            return -1;
3362
    } else if (dev->type == VIR_DOMAIN_DEVICE_NET) {
3363
        char mac[VIR_MAC_STRING_BUFLEN];
3364 3365
        virDomainNetDefPtr netdef = dev->data.net;
        virMacAddrFormat(&netdef->mac, mac);
3366 3367 3368

        strcpy(class, "vif");

D
Daniel P. Berrange 已提交
3369
        xenUnifiedLock(priv);
3370
        xref = xenStoreDomainGetNetworkID(conn, def->id, mac);
D
Daniel P. Berrange 已提交
3371
        xenUnifiedUnlock(priv);
3372 3373 3374
        if (xref == NULL)
            return -1;

C
Chris Lalancette 已提交
3375
        tmp = virStrcpy(ref, xref, ref_len);
3376
        VIR_FREE(xref);
C
Chris Lalancette 已提交
3377 3378
        if (tmp == NULL)
            return -1;
3379 3380 3381
    } 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) {
3382
        char *bdf;
3383
        virDomainHostdevDefPtr hostdef = dev->data.hostdev;
3384 3385

        if (virAsprintf(&bdf, "%04x:%02x:%02x.%0x",
3386 3387 3388
                        hostdef->source.subsys.u.pci.addr.domain,
                        hostdef->source.subsys.u.pci.addr.bus,
                        hostdef->source.subsys.u.pci.addr.slot,
3389
                        hostdef->source.subsys.u.pci.addr.function) < 0)
3390 3391 3392 3393 3394
            return -1;

        strcpy(class, "pci");

        xenUnifiedLock(priv);
3395
        xref = xenStoreDomainGetPCIID(conn, def->id, bdf);
3396 3397 3398 3399 3400 3401 3402 3403 3404
        xenUnifiedUnlock(priv);
        VIR_FREE(bdf);
        if (xref == NULL)
            return -1;

        tmp = virStrcpy(ref, xref, ref_len);
        VIR_FREE(xref);
        if (tmp == NULL)
            return -1;
3405
    } else {
3406 3407
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("hotplug of device type not supported"));
3408 3409 3410 3411 3412
        return -1;
    }

    return 0;
}