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

22
#include <config.h>
23

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

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

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

64 65
#define VIR_FROM_THIS VIR_FROM_XEND

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

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

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

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

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

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

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

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

    return s;
}

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

    while (offset < size) {
        ssize_t len;

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

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

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

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

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

        offset += len;
    }

    return offset;
}

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

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

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

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

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

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

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

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

    return offset;
}
258 259 260 261

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

265

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

286
    if (VIR_ALLOC_N(buffer, buffer_size) < 0)
287 288 289
        return -1;

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

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

299 300
    VIR_FREE(buffer);

301
    if (content_length > 0) {
302 303
        ssize_t ret;

J
Jim Fehlig 已提交
304
        if (content_length > XEND_RCV_BUF_MAX_LEN) {
305 306 307 308 309
            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 已提交
310 311 312 313 314 315
            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. */
316
        if (VIR_ALLOC_N(*content, content_length + 1) < 0)
317
            return -1;
318

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

    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 已提交
337
static int ATTRIBUTE_NONNULL(3)
338
xend_get(virConnectPtr xend, const char *path, char **content)
339 340 341 342 343 344 345
{
    int ret;
    int s = do_connect(xend);

    if (s == -1)
        return s;

346 347 348
    swrites(s, "GET ");
    swrites(s, path);
    swrites(s, " HTTP/1.1\r\n");
349

350
    swrites(s,
351 352 353 354
            "Host: localhost:8000\r\n"
            "Accept-Encoding: identity\r\n"
            "Content-Type: application/x-www-form-urlencoded\r\n" "\r\n");

355
    ret = xend_req(s, content);
356
    VIR_FORCE_CLOSE(s);
357

358 359 360 361
    if (ret < 0)
        return ret;

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

367 368 369 370 371 372 373
    return ret;
}

/**
 * xend_post:
 * @xend: pointer to the Xen Daemon structure
 * @path: the path used for the HTTP request
374
 * @ops: the information sent for the POST
375 376 377 378 379 380 381
 *
 * 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
382
xend_post(virConnectPtr xend, const char *path, const char *ops)
383 384
{
    char buffer[100];
385
    char *err_buf = NULL;
386 387 388 389 390 391
    int ret;
    int s = do_connect(xend);

    if (s == -1)
        return s;

392 393 394
    swrites(s, "POST ");
    swrites(s, path);
    swrites(s, " HTTP/1.1\r\n");
395

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

406
    ret = xend_req(s, &err_buf);
407
    VIR_FORCE_CLOSE(s);
408

D
Daniel Veillard 已提交
409
    if ((ret < 0) || (ret >= 300)) {
410 411
        virReportError(VIR_ERR_POST_FAILED,
                       _("xend_post: error from xen daemon: %s"), err_buf);
412
    } else if ((ret == 202) && err_buf && (strstr(err_buf, "failed") != NULL)) {
413 414
        virReportError(VIR_ERR_POST_FAILED,
                       _("xend_post: error from xen daemon: %s"), err_buf);
415
        ret = -1;
416 417
    } else if (((ret >= 200) && (ret <= 202)) && err_buf &&
               (strstr(err_buf, "xend.err") != NULL)) {
418 419 420
        /* 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 :-(
421
         */
422 423
        virReportError(VIR_ERR_POST_FAILED,
                       _("xend_post: error from xen daemon: %s"), err_buf);
424
        ret = -1;
D
Daniel Veillard 已提交
425 426
    }

427
    VIR_FREE(err_buf);
428 429
    return ret;
}
430

431 432 433 434 435 436 437 438 439 440

/**
 * 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
441
http2unix(int ret)
442 443 444 445 446 447 448 449 450 451 452
{
    switch (ret) {
        case -1:
            break;
        case 200:
        case 201:
        case 202:
            return 0;
        case 404:
            errno = ESRCH;
            break;
453 454 455
        case 500:
            errno = EIO;
            break;
456
        default:
457 458
            virReportError(VIR_ERR_HTTP_ERROR,
                           _("Unexpected HTTP error code %d"), ret);
459 460 461 462 463 464 465
            errno = EINVAL;
            break;
    }
    return -1;
}

/**
466
 * xend_op_ext:
467 468 469 470 471 472 473 474 475 476
 * @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
477
xend_op_ext(virConnectPtr xend, const char *path, const char *key, va_list ap)
478 479
{
    const char *k = key, *v;
480
    virBuffer buf = VIR_BUFFER_INITIALIZER;
481
    int ret;
482
    char *content;
483 484 485 486

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

P
Philipp Hahn 已提交
487 488 489
        virBufferURIEncodeString(&buf, k);
        virBufferAddChar(&buf, '=');
        virBufferURIEncodeString(&buf, v);
490 491 492
        k = va_arg(ap, const char *);

        if (k)
493
            virBufferAddChar(&buf, '&');
494 495
    }

496
    if (virBufferError(&buf)) {
497
        virBufferFreeAndReset(&buf);
498
        virReportOOMError();
499 500 501 502
        return -1;
    }

    content = virBufferContentAndReset(&buf);
503
    VIR_DEBUG("xend op: %s\n", content);
504
    ret = http2unix(xend_post(xend, path, content));
505
    VIR_FREE(content);
506 507

    return ret;
508 509
}

510

511
/**
512
 * xend_op:
513 514 515 516 517 518 519 520 521 522 523
 * @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 已提交
524
static int ATTRIBUTE_SENTINEL
525
xend_op(virConnectPtr xend, const char *name, const char *key, ...)
526 527 528 529 530 531 532 533
{
    char buffer[1024];
    va_list ap;
    int ret;

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

    va_start(ap, key);
534
    ret = xend_op_ext(xend, buffer, key, ap);
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
    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
 */
551
static struct sexpr *sexpr_get(virConnectPtr xend, const char *fmt, ...)
E
Eric Blake 已提交
552
  ATTRIBUTE_FMT_PRINTF(2, 3);
553

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

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

567
    ret = xend_get(xend, path, &buffer);
568
    ret = http2unix(ret);
569
    if (ret == -1)
570 571 572 573 574 575
        goto cleanup;

    if (buffer == NULL)
        goto cleanup;

    res = string2sexpr(buffer);
576

577 578 579
cleanup:
    VIR_FREE(buffer);
    return res;
580 581 582 583 584 585 586 587 588 589
}

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

/* PUBLIC FUNCTIONS */

/**
604
 * xenDaemonOpen_unix:
605
 * @conn: an existing virtual connection block
606 607 608 609 610
 * @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
 *
611
 * Returns 0 in case of success, -1 in case of error.
612
 */
613
int
614
xenDaemonOpen_unix(virConnectPtr conn, const char *path)
615 616
{
    struct sockaddr_un *addr;
617
    xenUnifiedPrivatePtr priv = conn->privateData;
618

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

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

634
    return 0;
635 636
}

637

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

658 659 660
    priv->addrlen = 0;
    memset(&priv->addr, 0, sizeof(priv->addr));

661
    /* http://people.redhat.com/drepper/userapi-ipv6.html */
662
    memset (&hints, 0, sizeof(hints));
663 664 665 666 667
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_ADDRCONFIG;

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

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

678
        sock = socket(r->ai_family, SOCK_STREAM, r->ai_protocol);
679 680 681
        if (sock == -1) {
            saved_errno = errno;
            continue;
682
        }
683

684
        if (connect(sock, r->ai_addr, r->ai_addrlen) == -1) {
685
            saved_errno = errno;
686
            VIR_FORCE_CLOSE(sock);
687 688 689 690 691 692 693 694 695
            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);
696
        VIR_FORCE_CLOSE(sock);
697
        break;
698 699
    }

700
    freeaddrinfo(res);
701

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

711
    return 0;
712 713
}

714

715 716
/**
 * xend_wait_for_devices:
P
Philipp Hahn 已提交
717
 * @xend: pointer to the Xen Daemon block
718 719 720 721 722 723 724 725
 * @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
726
xend_wait_for_devices(virConnectPtr xend, const char *name)
727 728 729 730
{
    return xend_op(xend, name, "op", "wait_for_devices", NULL);
}

731

732
/**
733
 * xenDaemonListDomainsOld:
P
Philipp Hahn 已提交
734
 * @xend: pointer to the Xen Daemon block
735 736 737 738 739 740
 *
 * 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.
 */
741
char **
742
xenDaemonListDomainsOld(virConnectPtr xend)
743 744 745 746
{
    struct sexpr *root = NULL;
    char **ret = NULL;
    int count = 0;
747
    size_t i;
748 749 750 751 752 753
    struct sexpr *_for_i, *node;

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

754 755
    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) {
756 757 758 759 760
        if (node->kind != SEXPR_VALUE)
            continue;
        count++;
    }

761
    if (VIR_ALLOC_N(ret, count + 1) < 0)
762 763 764
        goto error;

    i = 0;
765 766
    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) {
767 768
        if (node->kind != SEXPR_VALUE)
            continue;
769
        if (VIR_STRDUP(ret[i], node->u.value) < 0)
E
Eric Blake 已提交
770
            goto no_memory;
771 772 773 774 775 776 777 778
        i++;
    }

    ret[i] = NULL;

  error:
    sexpr_free(root);
    return ret;
E
Eric Blake 已提交
779 780 781 782 783 784

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

787

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

int
803
xenDaemonDomainCreateXML(virConnectPtr xend, const char *sexpr)
804
{
P
Philipp Hahn 已提交
805
    int ret;
806

P
Philipp Hahn 已提交
807
    ret = xend_op(xend, "", "op", "create", "config", sexpr, NULL);
808 809 810

    return ret;
}
811

812

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

832
    if (uuid != NULL)
833
        memset(uuid, 0, VIR_UUID_BUFLEN);
834 835 836 837 838
    root = sexpr_get(xend, "/xend/domain/%s?detail=1", domname);
    if (root == NULL)
        goto error;

    value = sexpr_node(root, "domain/domid");
839
    if (value == NULL) {
840 841
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("domain information incomplete, missing domid"));
842
        goto error;
843
    }
844
    ret = strtol(value, NULL, 0);
845
    if ((ret == 0) && (value[0] != '0')) {
846 847
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("domain information incorrect domid not numeric"));
848
        ret = -1;
849
    } else if (uuid != NULL) {
850
        if (sexpr_uuid(uuid, root, "domain/uuid") < 0) {
851 852
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("domain information incomplete, missing uuid"));
853
        }
854
    }
855

856
  error:
857
    sexpr_free(root);
858
    return ret;
859 860
}

861

862
static int
863 864
xend_detect_config_version(virConnectPtr conn)
{
865 866
    struct sexpr *root;
    const char *value;
867
    xenUnifiedPrivatePtr priv = conn->privateData;
868

869 870
    root = sexpr_get(conn, "/xend/node/");
    if (root == NULL)
871
        return -1;
872

873
    value = sexpr_node(root, "node/xend_config_format");
874

875
    if (value) {
876
        priv->xendConfigVersion = strtol(value, NULL, 10);
877 878 879
    }  else {
        /* Xen prior to 3.0.3 did not have the xend_config_format
           field, and is implicitly version 1. */
880
        priv->xendConfigVersion = XEND_CONFIG_VERSION_3_0_2;
881
    }
882
    sexpr_free(root);
883
    return 0;
884 885
}

D
Daniel Veillard 已提交
886

887 888 889 890 891 892 893 894 895 896
/**
 * 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)
897
sexpr_to_xend_domain_state(virDomainDefPtr def, const struct sexpr *root)
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
{
    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;
915
    } else if (def->id < 0 || sexpr_int(root, "domain/status") == 0) {
916 917 918 919 920 921 922
        /* 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)
         */
923 924 925 926 927 928
        state = VIR_DOMAIN_SHUTOFF;
    }

    return state;
}

D
Daniel Veillard 已提交
929
/**
930 931 932 933 934 935 936 937 938 939
 * 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
940
sexpr_to_xend_domain_info(virDomainDefPtr def,
941
                          const struct sexpr *root,
942
                          virDomainInfoPtr info)
943
{
944
    int vcpus;
945

946
    info->state = sexpr_to_xend_domain_state(def, root);
947 948 949
    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;
950

951
    vcpus = sexpr_int(root, "domain/vcpus");
952
    info->nrVirtCpu = count_one_bits_l(sexpr_u64(root, "domain/vcpu_avail"));
953 954 955
    if (!info->nrVirtCpu || vcpus < info->nrVirtCpu)
        info->nrVirtCpu = vcpus;

956
    return 0;
957 958
}

959 960 961 962 963 964 965 966 967 968 969
/**
 * 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
970
sexpr_to_xend_node_info(const struct sexpr *root, virNodeInfoPtr info)
971 972 973 974
{
    const char *machine;

    machine = sexpr_node(root, "node/machine");
975
    if (machine == NULL) {
976
        info->model[0] = 0;
977
    } else {
978
        snprintf(&info->model[0], sizeof(info->model) - 1, "%s", machine);
979
        info->model[sizeof(info->model) - 1] = 0;
980 981 982 983 984 985 986
    }
    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");
987 988 989
    info->cores = sexpr_int(root, "node/cores_per_socket");
    info->threads = sexpr_int(root, "node/threads_per_core");

990 991 992 993 994 995 996
    /* 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");
997 998
        int procs = info->nodes * info->cores * info->threads;
        if (procs == 0) /* Sanity check in case of Xen bugs in futures..*/
999
            return -1;
1000
        info->sockets = nr_cpus / procs;
1001
    }
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015

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

1016
    return 0;
1017 1018
}

1019

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

    nodeToCpu = sexpr_node(root, "node/node_to_cpu");
1043 1044
    if (nodeToCpu == NULL)
        return 0;               /* no NUMA support */
1045 1046 1047

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

1048 1049 1050

    cur = nodeToCpu;
    while (*cur != 0) {
1051
        virBitmapPtr cpuset = NULL;
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
        /*
         * 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 已提交
1062
        virSkipSpacesAndBackslash(&cur);
1063 1064 1065
        if (*cur != ':')
            goto parse_error;
        cur++;
E
Eric Blake 已提交
1066
        virSkipSpacesAndBackslash(&cur);
1067
        if (STRPREFIX(cur, "no cpus")) {
1068
            nb_cpus = 0;
1069
            if (!(cpuset = virBitmapNew(numCpus)))
1070
                goto error;
1071
        } else {
1072
            nb_cpus = virBitmapParse(cur, 'n', &cpuset, numCpus);
1073 1074 1075 1076
            if (nb_cpus < 0)
                goto error;
        }

1077 1078
        if (VIR_ALLOC_N(cpuInfo, numCpus) < 0) {
            virBitmapFree(cpuset);
1079
            goto error;
1080
        }
1081

1082 1083 1084 1085 1086
        for (n = 0, cpu = 0; cpu < numCpus; cpu++) {
            bool used;

            ignore_value(virBitmapGetBit(cpuset, cpu, &used));
            if (used)
1087
                cpuInfo[n++].id = cpu;
1088
        }
1089
        virBitmapFree(cpuset);
1090

1091
        if (virCapabilitiesAddHostNUMACell(caps, cell, nb_cpus, 0, cpuInfo) < 0)
1092
            goto error;
1093
        cpuInfo = NULL;
1094
    }
1095

1096
    return 0;
1097

1098
  parse_error:
1099
    virReportError(VIR_ERR_XEN_CALL, "%s", _("topology syntax error"));
1100
  error:
1101 1102
    virCapabilitiesClearHostNUMACellCPUTopology(cpuInfo, nb_cpus);
    VIR_FREE(cpuInfo);
1103
    return -1;
1104 1105
}

1106

1107 1108 1109 1110 1111 1112 1113
/**
 * 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
 *
1114
 * Returns the domain def pointer or NULL in case of error.
1115
 */
1116
static virDomainDefPtr
1117
sexpr_to_domain(virConnectPtr conn, const struct sexpr *root)
1118
{
1119
    virDomainDefPtr ret = NULL;
1120
    unsigned char uuid[VIR_UUID_BUFLEN];
1121
    const char *name;
1122
    const char *tmp;
1123
    int id = -1;
1124
    xenUnifiedPrivatePtr priv = conn->privateData;
1125

1126
    if (sexpr_uuid(uuid, root, "domain/uuid") < 0)
1127 1128 1129 1130 1131
        goto error;
    name = sexpr_node(root, "domain/name");
    if (name == NULL)
        goto error;

1132 1133 1134 1135
    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
     */
1136
    if (!tmp && priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4)
1137 1138
        goto error;

1139
    if (tmp)
1140
        id = sexpr_int(root, "domain/domid");
1141

1142
    return virDomainDefNew(name, uuid, id);
1143

1144
error:
1145 1146
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("failed to parse Xend domain information"));
1147
    virObjectUnref(ret);
1148
    return NULL;
1149
}
1150

1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172

/*****************************************************************
 ******
 ******
 ******
 ******
             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.
 */
1173
int
1174 1175
xenDaemonOpen(virConnectPtr conn,
              virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
1176
              unsigned int flags)
1177
{
1178
    char *port = NULL;
1179
    int ret = -1;
1180

1181
    virCheckFlags(VIR_CONNECT_RO, -1);
E
Eric Blake 已提交
1182

1183 1184
    /* Switch on the scheme, which we expect to be NULL (file),
     * "http" or "xen".
1185
     */
1186
    if (conn->uri->scheme == NULL) {
1187
        /* It should be a file access */
1188
        if (conn->uri->path == NULL) {
1189
            virReportError(VIR_ERR_NO_CONNECT, __FUNCTION__);
1190 1191
            goto failed;
        }
1192 1193
        if (xenDaemonOpen_unix(conn, conn->uri->path) < 0 ||
            xend_detect_config_version(conn) == -1)
1194 1195
            goto failed;
    }
1196
    else if (STRCASEEQ(conn->uri->scheme, "xen")) {
1197
        /*
1198 1199
         * try first to open the unix socket
         */
1200 1201
        if (xenDaemonOpen_unix(conn, "/var/lib/xend/xend-socket") == 0 &&
            xend_detect_config_version(conn) != -1)
1202 1203 1204 1205 1206
            goto done;

        /*
         * try though http on port 8000
         */
1207 1208
        if (xenDaemonOpen_tcp(conn, "localhost", "8000") < 0 ||
            xend_detect_config_version(conn) == -1)
1209
            goto failed;
1210
    } else if (STRCASEEQ(conn->uri->scheme, "http")) {
1211
        if (conn->uri->port &&
1212
            virAsprintf(&port, "%d", conn->uri->port) == -1)
1213
            goto failed;
1214

1215 1216 1217
        if (xenDaemonOpen_tcp(conn,
                              conn->uri->server ? conn->uri->server : "localhost",
                              port ? port : "8000") < 0 ||
1218
            xend_detect_config_version(conn) == -1)
1219
            goto failed;
1220
    } else {
1221
        virReportError(VIR_ERR_NO_CONNECT, __FUNCTION__);
1222
        goto failed;
1223
    }
1224

1225
 done:
1226
    ret = 0;
1227

1228
failed:
1229 1230
    VIR_FREE(port);
    return ret;
1231
}
1232

1233 1234 1235 1236 1237 1238 1239 1240 1241

/**
 * 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.
 *
1242
 * Returns 0 in case of success, -1 in case of error
1243 1244 1245 1246
 */
int
xenDaemonClose(virConnectPtr conn ATTRIBUTE_UNUSED)
{
1247
    return 0;
1248 1249 1250 1251
}

/**
 * xenDaemonDomainSuspend:
1252 1253
 * @conn: the connection object
 * @def: the domain to suspend
1254 1255 1256 1257 1258 1259 1260
 *
 * 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
1261
xenDaemonDomainSuspend(virConnectPtr conn, virDomainDefPtr def)
1262
{
1263
    if (def->id < 0) {
1264
        virReportError(VIR_ERR_OPERATION_INVALID,
1265
                       _("Domain %s isn't running."), def->name);
1266
        return -1;
1267 1268
    }

1269
    return xend_op(conn, def->name, "op", "pause", NULL);
1270 1271 1272 1273
}

/**
 * xenDaemonDomainResume:
1274 1275
 * @conn: the connection object
 * @def: the domain to resume
1276 1277 1278 1279 1280 1281
 *
 * Resume the domain after xenDaemonDomainSuspend() has been called
 *
 * Returns 0 in case of success, -1 (with errno) in case of error.
 */
int
1282
xenDaemonDomainResume(virConnectPtr conn, virDomainDefPtr def)
1283
{
1284
    if (def->id < 0) {
1285
        virReportError(VIR_ERR_OPERATION_INVALID,
1286
                       _("Domain %s isn't running."), def->name);
1287
        return -1;
1288 1289
    }

1290
    return xend_op(conn, def->name, "op", "unpause", NULL);
1291 1292 1293 1294
}

/**
 * xenDaemonDomainShutdown:
1295 1296
 * @conn: the connection object
 * @def: the domain to shutdown
1297 1298 1299 1300 1301 1302 1303 1304
 *
 * 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
1305
xenDaemonDomainShutdown(virConnectPtr conn, virDomainDefPtr def)
1306
{
1307
    if (def->id < 0) {
1308
        virReportError(VIR_ERR_OPERATION_INVALID,
1309
                       _("Domain %s isn't running."), def->name);
1310
        return -1;
1311 1312
    }

1313
    return xend_op(conn, def->name, "op", "shutdown", "reason", "poweroff", NULL);
1314 1315
}

1316 1317
/**
 * xenDaemonDomainReboot:
1318 1319
 * @conn: the connection object
 * @def: the domain to reboot
1320 1321 1322 1323 1324 1325 1326 1327
 *
 * 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
1328
xenDaemonDomainReboot(virConnectPtr conn, virDomainDefPtr def)
1329
{
1330
    if (def->id < 0) {
1331
        virReportError(VIR_ERR_OPERATION_INVALID,
1332
                       _("Domain %s isn't running."), def->name);
1333
        return -1;
1334 1335
    }

1336
    return xend_op(conn, def->name, "op", "shutdown", "reason", "reboot", NULL);
1337 1338
}

1339
/**
1340
 * xenDaemonDomainDestroy:
1341 1342
 * @conn: the connection object
 * @def: the domain to destroy
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
 *
 * 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
1354
xenDaemonDomainDestroy(virConnectPtr conn, virDomainDefPtr def)
1355
{
1356
    if (def->id < 0) {
1357
        virReportError(VIR_ERR_OPERATION_INVALID,
1358
                       _("Domain %s isn't running."), def->name);
1359
        return -1;
1360 1361
    }

1362
    return xend_op(conn, def->name, "op", "destroy", NULL);
1363 1364
}

1365 1366 1367 1368 1369 1370 1371 1372 1373
/**
 * 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.
 */
1374
char *
1375 1376
xenDaemonDomainGetOSType(virConnectPtr conn,
                         virDomainDefPtr def)
1377 1378 1379 1380 1381
{
    char *type;
    struct sexpr *root;

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

1386 1387
    ignore_value(VIR_STRDUP(type,
                            sexpr_lookup(root, "domain/image/hvm") ? "hvm" : "linux"));
1388

1389 1390
    sexpr_free(root);

1391
    return type;
1392 1393
}

1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
/**
 * 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
1408 1409 1410
xenDaemonDomainSave(virConnectPtr conn,
                    virDomainDefPtr def,
                    const char *filename)
1411
{
1412
    if (def->id < 0) {
1413
        virReportError(VIR_ERR_OPERATION_INVALID,
1414
                       _("Domain %s isn't running."), def->name);
1415
        return -1;
1416
    }
1417 1418

    /* We can't save the state of Domain-0, that would mean stopping it too */
1419
    if (def->id == 0) {
1420 1421
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Cannot save host domain"));
1422
        return -1;
1423 1424
    }

1425
    return xend_op(conn, def->name, "op", "save", "file", filename, NULL);
1426 1427
}

D
Daniel Veillard 已提交
1428 1429
/**
 * xenDaemonDomainCoreDump:
1430 1431
 * @conn: the connection object
 * @def: domain configuration
D
Daniel Veillard 已提交
1432 1433 1434 1435 1436 1437 1438 1439 1440
 * @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.
 */
1441
int
1442 1443
xenDaemonDomainCoreDump(virConnectPtr conn,
                        virDomainDefPtr def,
1444
                        const char *filename,
E
Eric Blake 已提交
1445
                        unsigned int flags)
D
Daniel Veillard 已提交
1446
{
E
Eric Blake 已提交
1447 1448
    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH, -1);

1449
    if (def->id < 0) {
1450
        virReportError(VIR_ERR_OPERATION_INVALID,
1451
                       _("Domain %s isn't running."), def->name);
1452
        return -1;
1453 1454
    }

1455
    return xend_op(conn, def->name,
J
Jiri Denemark 已提交
1456
                   "op", "dump", "file", filename,
P
Paolo Bonzini 已提交
1457
                   "live", (flags & VIR_DUMP_LIVE ? "1" : "0"),
1458 1459
                   "crash", (flags & VIR_DUMP_CRASH ? "1" : "0"),
                   NULL);
D
Daniel Veillard 已提交
1460 1461
}

1462 1463
/**
 * xenDaemonDomainRestore:
P
Philipp Hahn 已提交
1464
 * @conn: pointer to the Xen Daemon block
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
 * @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);
}
1478

1479

1480 1481 1482 1483 1484 1485 1486 1487
/**
 * 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.
 */
1488
unsigned long long
1489
xenDaemonDomainGetMaxMemory(virConnectPtr conn, virDomainDefPtr def)
1490
{
1491
    unsigned long long ret = 0;
1492 1493 1494
    struct sexpr *root;

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

1499
    ret = sexpr_u64(root, "domain/memory") << 10;
1500 1501
    sexpr_free(root);

1502
    return ret;
1503 1504
}

1505

1506 1507 1508 1509 1510 1511 1512
/**
 * 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
1513
 * on its own.
1514 1515 1516 1517
 *
 * Returns 0 for success; -1 (with errno) on error
 */
int
1518 1519 1520
xenDaemonDomainSetMaxMemory(virConnectPtr conn,
                            virDomainDefPtr def,
                            unsigned long memory)
1521 1522
{
    char buf[1024];
1523

1524
    snprintf(buf, sizeof(buf), "%lu", VIR_DIV_UP(memory, 1024));
1525
    return xend_op(conn, def->name, "op", "maxmem_set", "memory",
1526 1527 1528
                   buf, NULL);
}

1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
/**
 * 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
1546 1547 1548
xenDaemonDomainSetMemory(virConnectPtr conn,
                         virDomainDefPtr def,
                         unsigned long memory)
1549 1550
{
    char buf[1024];
1551

1552
    snprintf(buf, sizeof(buf), "%lu", VIR_DIV_UP(memory, 1024));
1553
    return xend_op(conn, def->name, "op", "mem_target_set",
1554 1555 1556
                   "target", buf, NULL);
}

1557

1558
virDomainDefPtr
1559
xenDaemonDomainFetch(virConnectPtr conn, int domid, const char *name,
1560
                     const char *cpus)
1561 1562
{
    struct sexpr *root;
1563
    xenUnifiedPrivatePtr priv = conn->privateData;
1564
    virDomainDefPtr def = NULL;
1565 1566 1567
    int id;
    char * tty;
    int vncport;
1568

1569 1570 1571 1572
    if (name)
        root = sexpr_get(conn, "/xend/domain/%s?detail=1", name);
    else
        root = sexpr_get(conn, "/xend/domain/%d?detail=1", domid);
1573
    if (root == NULL)
1574
        return NULL;
1575

1576 1577
    if (xenGetDomIdFromSxpr(root, priv->xendConfigVersion, &id) < 0)
        goto cleanup;
1578
    xenUnifiedLock(priv);
1579 1580 1581 1582
    if (sexpr_lookup(root, "domain/image/hvm"))
        tty = xenStoreDomainGetSerialConsolePath(conn, id);
    else
        tty = xenStoreDomainGetConsolePath(conn, id);
1583 1584
    vncport = xenStoreDomainGetVNCPort(conn, id);
    xenUnifiedUnlock(priv);
M
Markus Groß 已提交
1585 1586 1587 1588 1589
    if (!(def = xenParseSxpr(root,
                             priv->xendConfigVersion,
                             cpus,
                             tty,
                             vncport)))
1590 1591 1592
        goto cleanup;

cleanup:
1593 1594
    sexpr_free(root);

1595
    return def;
1596 1597 1598
}


1599
/**
1600
 * xenDaemonDomainGetXMLDesc:
D
Daniel Veillard 已提交
1601
 * @domain: a domain object
1602
 * @cpus: list of cpu the domain is pinned to.
D
Daniel Veillard 已提交
1603
 *
1604
 * Get the XML description of the domain as a structure.
D
Daniel Veillard 已提交
1605
 *
1606
 * Returns a virDomainDefPtr instance, or NULL in case of error.
D
Daniel Veillard 已提交
1607
 */
1608 1609 1610
virDomainDefPtr
xenDaemonDomainGetXMLDesc(virConnectPtr conn,
                          virDomainDefPtr minidef,
E
Eric Blake 已提交
1611
                          const char *cpus)
1612
{
1613 1614 1615 1616
    return xenDaemonDomainFetch(conn,
                                minidef->id,
                                minidef->name,
                                cpus);
D
Daniel Veillard 已提交
1617
}
1618

1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630

/**
 * 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
1631 1632 1633
xenDaemonDomainGetInfo(virConnectPtr conn,
                       virDomainDefPtr def,
                       virDomainInfoPtr info)
1634 1635 1636 1637
{
    struct sexpr *root;
    int ret;

1638
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
1639
    if (root == NULL)
1640
        return -1;
1641

1642
    ret = sexpr_to_xend_domain_info(def, root, info);
1643
    sexpr_free(root);
1644
    return ret;
1645
}
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658


/**
 * 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
1659 1660
xenDaemonDomainGetState(virConnectPtr conn,
                        virDomainDefPtr def,
1661
                        int *state,
1662
                        int *reason)
1663 1664 1665
{
    struct sexpr *root;

1666
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
1667 1668 1669
    if (!root)
        return -1;

1670
    *state = sexpr_to_xend_domain_state(def, root);
1671 1672 1673 1674 1675 1676
    if (reason)
        *reason = 0;

    sexpr_free(root);
    return 0;
}
1677

1678

1679
/**
1680
 * xenDaemonLookupByName:
1681 1682 1683 1684 1685 1686 1687
 * @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.
 *
1688
 * Returns domain def pointer on success; NULL on error
1689
 */
1690
virDomainDefPtr
1691
xenDaemonLookupByName(virConnectPtr conn, const char *domname)
1692 1693
{
    struct sexpr *root;
1694
    virDomainDefPtr ret = NULL;
1695 1696 1697 1698 1699 1700 1701 1702 1703

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

    ret = sexpr_to_domain(conn, root);

error:
    sexpr_free(root);
1704
    return ret;
1705
}
1706

1707

1708 1709 1710 1711
/**
 * xenDaemonNodeGetInfo:
 * @conn: pointer to the Xen Daemon block
 * @info: pointer to a virNodeInfo structure allocated by the user
1712
 *
1713 1714 1715 1716
 * Extract hardware information about the node.
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
1717
int
1718 1719
xenDaemonNodeGetInfo(virConnectPtr conn, virNodeInfoPtr info)
{
1720 1721 1722 1723 1724
    int ret = -1;
    struct sexpr *root;

    root = sexpr_get(conn, "/xend/node/");
    if (root == NULL)
1725
        return -1;
1726 1727 1728

    ret = sexpr_to_xend_node_info(root, info);
    sexpr_free(root);
1729
    return ret;
1730 1731
}

1732 1733 1734
/**
 * xenDaemonNodeGetTopology:
 * @conn: pointer to the Xen Daemon block
1735
 * @caps: capabilities info
1736 1737 1738 1739 1740 1741
 *
 * This method retrieves a node's topology information.
 *
 * Returns -1 in case of error, 0 otherwise.
 */
int
1742 1743
xenDaemonNodeGetTopology(virConnectPtr conn, virCapsPtr caps)
{
1744 1745 1746 1747 1748
    int ret = -1;
    struct sexpr *root;

    root = sexpr_get(conn, "/xend/node/");
    if (root == NULL) {
1749
        return -1;
1750 1751
    }

1752
    ret = sexpr_to_xend_topology(root, caps);
1753
    sexpr_free(root);
1754
    return ret;
1755 1756
}

1757

1758 1759
/**
 * xenDaemonDomainSetVcpusFlags:
1760 1761
 * @conn: the connection object
 * @def: domain configuration
1762 1763 1764 1765 1766
 * @nvcpus: the new number of virtual CPUs for this domain
 * @flags: bitwise-ORd from virDomainVcpuFlags
 *
 * Change virtual CPUs allocation of domain according to flags.
 *
1767
 * Returns 0 on success, -1 if an error message was issued
1768 1769
 */
int
1770 1771
xenDaemonDomainSetVcpusFlags(virConnectPtr conn,
                             virDomainDefPtr def,
1772
                             unsigned int vcpus,
1773 1774 1775 1776 1777
                             unsigned int flags)
{
    char buf[VIR_UUID_BUFLEN];
    int max;

E
Eric Blake 已提交
1778 1779 1780 1781
    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
                  VIR_DOMAIN_VCPU_CONFIG |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

1782
    if (vcpus < 1) {
1783
        virReportError(VIR_ERR_INVALID_ARG, __FUNCTION__);
1784
        return -1;
1785 1786
    }

1787
    if (def->id < 0) {
1788
        if (flags & VIR_DOMAIN_VCPU_LIVE) {
1789 1790
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("domain not running"));
1791 1792 1793 1794 1795
            return -1;
        }
    } else {
        if ((flags & (VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG)) !=
            (VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG)) {
1796 1797 1798
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Xend only supports modifying both live and "
                             "persistent config"));
1799 1800 1801 1802 1803 1804
        }
    }

    /* Unfortunately, xend_op does not validate whether this exceeds
     * the maximum.  */
    flags |= VIR_DOMAIN_VCPU_MAXIMUM;
1805
    if ((max = xenDaemonDomainGetVcpusFlags(conn, def, flags)) < 0) {
1806 1807
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("could not determine max vcpus for the domain"));
1808 1809 1810
        return -1;
    }
    if (vcpus > max) {
1811 1812 1813
        virReportError(VIR_ERR_INVALID_ARG,
                       _("requested vcpus is greater than max allowable"
                         " vcpus for the domain: %d > %d"), vcpus, max);
1814 1815 1816 1817
        return -1;
    }

    snprintf(buf, sizeof(buf), "%d", vcpus);
1818
    return xend_op(conn, def->name, "op", "set_vcpus", "vcpus",
1819 1820 1821
                   buf, NULL);
}

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

1852
    if (maplen > (int)sizeof(cpumap_t)) {
1853
        virReportError(VIR_ERR_INVALID_ARG, __FUNCTION__);
1854
        return -1;
1855
    }
1856

1857
    if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4) {
H
Henrik Persson 已提交
1858 1859
        mapstr[0] = '[';
        mapstr[1] = 0;
1860
    } else {
H
Henrik Persson 已提交
1861
        mapstr[0] = 0;
1862 1863
    }

1864 1865 1866
    /* 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)) {
1867
        snprintf(buf, sizeof(buf), "%zu,", (8 * i) + j);
1868 1869
        strcat(mapstr, buf);
    }
1870
    if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4)
1871 1872 1873 1874
        mapstr[strlen(mapstr) - 1] = ']';
    else
        mapstr[strlen(mapstr) - 1] = 0;

1875
    snprintf(buf, sizeof(buf), "%d", vcpu);
1876

1877
    ret = xend_op(conn, minidef->name, "op", "pincpu", "vcpu", buf,
1878 1879
                  "cpumap", mapstr, NULL);

1880 1881 1882
    if (!(def = xenDaemonDomainFetch(conn,
                                     minidef->id,
                                     minidef->name,
1883 1884 1885 1886
                                     NULL)))
        goto cleanup;

    if (ret == 0) {
H
Hu Tao 已提交
1887
        if (!def->cputune.vcpupin) {
1888
            if (VIR_ALLOC(def->cputune.vcpupin) < 0)
H
Hu Tao 已提交
1889 1890 1891
                goto cleanup;
            def->cputune.nvcpupin = 0;
        }
1892
        if (virDomainVcpuPinAdd(&def->cputune.vcpupin,
H
Hu Tao 已提交
1893 1894 1895 1896
                                &def->cputune.nvcpupin,
                                cpumap,
                                maplen,
                                vcpu) < 0) {
1897 1898
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("failed to add vcpupin xml entry"));
1899
            return -1;
1900 1901 1902 1903 1904 1905 1906 1907
        }
    }

    return ret;

cleanup:
    virDomainDefFree(def);
    return -1;
1908 1909
}

1910 1911
/**
 * xenDaemonDomainGetVcpusFlags:
1912 1913
 * @conn: the connection object
 * @def: domain configuration
1914 1915 1916 1917 1918
 * @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
1919
 * issued
1920 1921 1922

 */
int
1923 1924 1925
xenDaemonDomainGetVcpusFlags(virConnectPtr conn,
                             virDomainDefPtr def,
                             unsigned int flags)
1926 1927 1928 1929
{
    struct sexpr *root;
    int ret;

E
Eric Blake 已提交
1930 1931 1932 1933
    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
                  VIR_DOMAIN_VCPU_CONFIG |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

1934
    if (def->id < 0 && (flags & VIR_DOMAIN_VCPU_LIVE)) {
1935 1936
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("domain not active"));
1937 1938 1939
        return -1;
    }

1940
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
1941 1942 1943 1944 1945
    if (root == NULL)
        return -1;

    ret = sexpr_int(root, "domain/vcpus");
    if (!(flags & VIR_DOMAIN_VCPU_MAXIMUM)) {
1946
        int vcpus = count_one_bits_l(sexpr_u64(root, "domain/vcpu_avail"));
1947 1948 1949 1950
        if (vcpus)
            ret = MIN(vcpus, ret);
    }
    if (!ret)
1951
        ret = -1;
1952 1953 1954 1955
    sexpr_free(root);
    return ret;
}

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

1990
    root = sexpr_get(conn, "/xend/domain/%s?op=vcpuinfo", def->name);
1991
    if (root == NULL)
1992
        return -1;
1993 1994

    if (cpumaps != NULL)
1995
        memset(cpumaps, 0, maxinfo * maplen);
1996 1997

    /* scan the sexprs from "(vcpu (number x)...)" and get parameter values */
1998 1999 2000
    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) &&
2001
            STREQ(s->u.s.car->u.s.car->u.value, "vcpu")) {
2002
            t = s->u.s.car;
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
            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
                 */
2019 2020 2021
                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) &&
2022
                        STREQ(t->u.s.car->u.s.car->u.value, "cpumap") &&
2023 2024
                        (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)
2025
                            if (t->u.s.car->kind == SEXPR_VALUE
2026
                                && virStrToLong_i(t->u.s.car->u.value, NULL, 10, &cpu) == 0
2027 2028 2029
                                && cpu >= 0
                                && (VIR_CPU_MAPLEN(cpu+1) <= maplen)) {
                                VIR_USE_CPU(cpumap, cpu);
2030 2031 2032
                            }
                        break;
                    }
2033 2034
            }

2035 2036 2037
            if (++nbinfo == maxinfo) break;
            ipt++;
        }
2038 2039
    }
    sexpr_free(root);
2040
    return nbinfo;
2041 2042
}

2043 2044 2045 2046 2047 2048 2049
/**
 * 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.
 *
2050
 * Returns domain def pointer on success; NULL on error
2051
 */
2052
virDomainDefPtr
2053 2054
xenDaemonLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
2055
    virDomainDefPtr ret;
2056 2057
    char *name = NULL;
    int id = -1;
2058
    xenUnifiedPrivatePtr priv = conn->privateData;
2059

2060
    /* Old approach for xen <= 3.0.3 */
2061
    if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4) {
2062 2063 2064 2065 2066 2067
        char **names, **tmp;
        unsigned char ident[VIR_UUID_BUFLEN];
        names = xenDaemonListDomainsOld(conn);
        tmp = names;

        if (names == NULL) {
2068
            return NULL;
2069 2070 2071 2072 2073
        }
        while (*tmp != NULL) {
            id = xenDaemonDomainLookupByName_ids(conn, *tmp, &ident[0]);
            if (id >= 0) {
                if (!memcmp(uuid, ident, VIR_UUID_BUFLEN)) {
E
Eric Blake 已提交
2074
                    name = *tmp;
2075 2076
                    break;
                }
2077
            }
2078
            tmp++;
2079
        }
E
Eric Blake 已提交
2080 2081 2082 2083 2084 2085
        tmp = names;
        while (*tmp) {
            if (*tmp != name)
                VIR_FREE(*tmp);
            tmp++;
        }
2086
        VIR_FREE(names);
2087 2088 2089 2090 2091
    } else { /* New approach for xen >= 3.0.4 */
        char *domname = NULL;
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        struct sexpr *root = NULL;

2092
        virUUIDFormat(uuid, uuidstr);
2093 2094
        root = sexpr_get(conn, "/xend/domain/%s?detail=1", uuidstr);
        if (root == NULL)
2095
            return NULL;
2096 2097 2098 2099 2100
        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;
2101

2102
        ignore_value(VIR_STRDUP(name, domname));
2103

2104
        sexpr_free(root);
2105 2106 2107
    }

    if (name == NULL)
2108
        return NULL;
2109

2110
    ret = virDomainDefNew(name, uuid, id);
2111

2112
    VIR_FREE(name);
2113
    return ret;
2114
}
2115 2116

/**
2117
 * xenDaemonCreateXML:
2118
 * @conn: pointer to the hypervisor connection
2119
 * @def: domain configuration
2120 2121 2122 2123
 * @flags: an optional set of virDomainFlags
 *
 * Launch a new Linux guest domain, based on an XML description similar
 * to the one returned by virDomainGetXMLDesc()
2124
 * This function may requires privileged access to the hypervisor.
2125
 *
2126 2127
 * Returns a new domain object or NULL in case of failure
 */
2128 2129
int
xenDaemonCreateXML(virConnectPtr conn, virDomainDefPtr def)
2130 2131 2132
{
    int ret;
    char *sexpr;
2133 2134
    const char *tmp;
    struct sexpr *root;
2135
    xenUnifiedPrivatePtr priv = conn->privateData;
2136

2137 2138 2139 2140 2141
    if (def->id != -1) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Domain %s is already running"),
                       def->name);
        return -1;
2142 2143
    }

2144 2145 2146
    if (!(sexpr = xenFormatSxpr(conn, def, priv->xendConfigVersion)))
        return -1;

2147
    ret = xenDaemonDomainCreateXML(conn, sexpr);
2148
    VIR_FREE(sexpr);
2149 2150 2151 2152
    if (ret != 0) {
        goto error;
    }

2153 2154
    /* This comes before wait_for_devices, to ensure that latter
       cleanup will destroy the domain upon failure */
2155 2156
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
    if (root == NULL)
2157 2158
        goto error;

2159 2160 2161 2162 2163 2164 2165 2166 2167 2168
    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");

2169
    if (xend_wait_for_devices(conn, def->name) < 0)
2170 2171
        goto error;

2172
    if (xenDaemonDomainResume(conn, def) < 0)
2173 2174
        goto error;

2175
    return 0;
2176

2177
  error:
2178
    /* Make sure we don't leave a still-born domain around */
2179
    if (def->id != -1)
2180
        xenDaemonDomainDestroy(conn, def);
2181
    return -1;
2182
}
2183 2184

/**
2185
 * xenDaemonAttachDeviceFlags:
2186 2187
 * @conn: the connection object
 * @minidef: domain configuration
2188
 * @xml: pointer to XML description of device
2189
 * @flags: an OR'ed set of virDomainDeviceModifyFlags
2190
 *
2191 2192 2193 2194 2195
 * 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.
 */
2196
int
2197 2198
xenDaemonAttachDeviceFlags(virConnectPtr conn,
                           virDomainDefPtr minidef,
2199
                           const char *xml,
2200
                           unsigned int flags)
2201
{
2202
    xenUnifiedPrivatePtr priv = conn->privateData;
2203 2204 2205 2206 2207
    char *sexpr = NULL;
    int ret = -1;
    virDomainDeviceDefPtr dev = NULL;
    virDomainDefPtr def = NULL;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
2208
    char class[8], ref[80];
2209
    char *target = NULL;
2210

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

2213
    if (minidef->id < 0) {
2214 2215
        /* Cannot modify live config if domain is inactive */
        if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
2216 2217
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Cannot modify live config if domain is inactive"));
2218 2219
            return -1;
        }
2220 2221
    } else {
        /* Only live config can be changed if xendConfigVersion < 3 */
2222
        if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4 &&
E
Eric Blake 已提交
2223
            (flags != VIR_DOMAIN_DEVICE_MODIFY_CURRENT &&
2224
             flags != VIR_DOMAIN_DEVICE_MODIFY_LIVE)) {
2225 2226 2227
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Xend version does not support modifying "
                             "persistent config"));
2228 2229
            return -1;
        }
2230
        /* Xen only supports modifying both live and persistent config if
2231 2232
         * xendConfigVersion >= 3
         */
2233
        if (priv->xendConfigVersion >= XEND_CONFIG_VERSION_3_0_4 &&
2234 2235
            (flags != (VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                       VIR_DOMAIN_DEVICE_MODIFY_CONFIG))) {
2236 2237 2238
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Xend only supports modifying both live and "
                             "persistent config"));
2239 2240 2241
            return -1;
        }
    }
2242

2243 2244 2245
    if (!(def = xenDaemonDomainFetch(conn,
                                     minidef->id,
                                     minidef->name,
2246 2247 2248
                                     NULL)))
        goto cleanup;

2249 2250
    if (!(dev = virDomainDeviceDefParse(xml, def, priv->caps, priv->xmlopt,
                                        VIR_DOMAIN_XML_INACTIVE)))
2251 2252 2253 2254 2255
        goto cleanup;


    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
2256 2257 2258 2259
        if (xenFormatSxprDisk(dev->data.disk,
                              &buf,
                              STREQ(def->os.type, "hvm") ? 1 : 0,
                              priv->xendConfigVersion, 1) < 0)
2260
            goto cleanup;
2261

2262 2263 2264
        if (dev->data.disk->device != VIR_DOMAIN_DISK_DEVICE_CDROM &&
            VIR_STRDUP(target, dev->data.disk->dst) < 0)
            goto cleanup;
2265
        break;
2266 2267

    case VIR_DOMAIN_DEVICE_NET:
2268
        if (xenFormatSxprNet(conn,
M
Markus Groß 已提交
2269 2270 2271 2272
                             dev->data.net,
                             &buf,
                             STREQ(def->os.type, "hvm") ? 1 : 0,
                             priv->xendConfigVersion, 1) < 0)
2273
            goto cleanup;
2274 2275

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

2278
        if (VIR_STRDUP(target, macStr) < 0)
2279
            goto cleanup;
2280
        break;
2281

2282 2283 2284
    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ß 已提交
2285
            if (xenFormatSxprOnePCI(dev->data.hostdev, &buf, 0) < 0)
2286
                goto cleanup;
2287

2288
            virDevicePCIAddress PCIAddr;
2289

2290
            PCIAddr = dev->data.hostdev->source.subsys.u.pci.addr;
2291
            if (virAsprintf(&target, "PCI device: %.4x:%.2x:%.2x",
2292
                            PCIAddr.domain, PCIAddr.bus, PCIAddr.slot) < 0)
2293
                goto cleanup;
2294
        } else {
2295 2296
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("unsupported device type"));
2297 2298 2299 2300
            goto cleanup;
        }
        break;

2301
    default:
2302 2303
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("unsupported device type"));
2304
        goto cleanup;
2305
    }
2306 2307 2308

    sexpr = virBufferContentAndReset(&buf);

2309
    if (virDomainXMLDevID(conn, minidef, dev, class, ref, sizeof(ref))) {
2310
        /* device doesn't exist, define it */
2311
        ret = xend_op(conn, def->name, "op", "device_create",
2312
                      "config", sexpr, NULL);
2313 2314
    } else {
        if (dev->data.disk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
2315 2316
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("target '%s' already exists"), target);
2317 2318
        } else {
            /* device exists, attempt to modify it */
2319
            ret = xend_op(conn, minidef->name, "op", "device_configure",
2320 2321
                          "config", sexpr, "dev", ref, NULL);
        }
2322
    }
2323 2324

cleanup:
2325
    VIR_FREE(sexpr);
2326 2327
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);
2328
    VIR_FREE(target);
2329 2330 2331
    return ret;
}

2332 2333
/**
 * xenDaemonUpdateDeviceFlags:
2334 2335
 * @conn: the connection object
 * @minidef: domain configuration
2336 2337 2338 2339 2340 2341 2342 2343
 * @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.
 */
2344
int
2345 2346
xenDaemonUpdateDeviceFlags(virConnectPtr conn,
                           virDomainDefPtr minidef,
2347
                           const char *xml,
2348 2349
                           unsigned int flags)
{
2350
    xenUnifiedPrivatePtr priv = conn->privateData;
2351 2352 2353 2354 2355 2356 2357
    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 已提交
2358
    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_LIVE |
2359 2360
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG, -1);

2361
    if (minidef->id < 0) {
2362 2363
        /* Cannot modify live config if domain is inactive */
        if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
2364 2365
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Cannot modify live config if domain is inactive"));
2366 2367
            return -1;
        }
2368 2369
    } else {
        /* Only live config can be changed if xendConfigVersion < 3 */
2370
        if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4 &&
E
Eric Blake 已提交
2371
            (flags != VIR_DOMAIN_DEVICE_MODIFY_CURRENT &&
2372
             flags != VIR_DOMAIN_DEVICE_MODIFY_LIVE)) {
2373 2374 2375
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Xend version does not support modifying "
                             "persistent config"));
2376 2377 2378 2379 2380
            return -1;
        }
        /* Xen only supports modifying both live and persistent config if
         * xendConfigVersion >= 3
         */
2381
        if (priv->xendConfigVersion >= XEND_CONFIG_VERSION_3_0_4 &&
2382 2383
            (flags != (VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                       VIR_DOMAIN_DEVICE_MODIFY_CONFIG))) {
2384 2385 2386
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Xend only supports modifying both live and "
                             "persistent config"));
2387 2388 2389 2390
            return -1;
        }
    }

2391 2392 2393
    if (!(def = xenDaemonDomainFetch(conn,
                                     minidef->id,
                                     minidef->name,
2394 2395 2396
                                     NULL)))
        goto cleanup;

2397 2398
    if (!(dev = virDomainDeviceDefParse(xml, def, priv->caps, priv->xmlopt,
                                        VIR_DOMAIN_XML_INACTIVE)))
2399 2400 2401 2402 2403
        goto cleanup;


    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
2404
        if (xenFormatSxprDisk(dev->data.disk,
M
Markus Groß 已提交
2405 2406 2407
                              &buf,
                              STREQ(def->os.type, "hvm") ? 1 : 0,
                              priv->xendConfigVersion, 1) < 0)
2408 2409 2410 2411
            goto cleanup;
        break;

    default:
2412 2413
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("unsupported device type"));
2414 2415 2416 2417 2418
        goto cleanup;
    }

    sexpr = virBufferContentAndReset(&buf);

2419
    if (virDomainXMLDevID(conn, minidef, dev, class, ref, sizeof(ref))) {
2420 2421
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("requested device does not exist"));
2422 2423 2424
        goto cleanup;
    } else {
        /* device exists, attempt to modify it */
2425
        ret = xend_op(conn, minidef->name, "op", "device_configure",
2426 2427 2428 2429 2430 2431 2432 2433 2434 2435
                      "config", sexpr, "dev", ref, NULL);
    }

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

2436
/**
2437
 * xenDaemonDetachDeviceFlags:
2438 2439
 * @conn: the connection object
 * @minidef: domain configuration
2440
 * @xml: pointer to XML description of device
2441
 * @flags: an OR'ed set of virDomainDeviceModifyFlags
2442
 *
2443 2444 2445 2446
 * Destroy a virtual device attachment to backend.
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
2447
int
2448 2449
xenDaemonDetachDeviceFlags(virConnectPtr conn,
                           virDomainDefPtr minidef,
2450
                           const char *xml,
2451
                           unsigned int flags)
2452
{
2453
    xenUnifiedPrivatePtr priv = conn->privateData;
2454
    char class[8], ref[80];
2455 2456 2457
    virDomainDeviceDefPtr dev = NULL;
    virDomainDefPtr def = NULL;
    int ret = -1;
2458 2459
    char *xendev = NULL;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
2460

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

2463
    if (minidef->id < 0) {
2464 2465
        /* Cannot modify live config if domain is inactive */
        if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
2466 2467
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Cannot modify live config if domain is inactive"));
2468 2469
            return -1;
        }
2470 2471
    } else {
        /* Only live config can be changed if xendConfigVersion < 3 */
2472
        if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4 &&
E
Eric Blake 已提交
2473
            (flags != VIR_DOMAIN_DEVICE_MODIFY_CURRENT &&
2474
             flags != VIR_DOMAIN_DEVICE_MODIFY_LIVE)) {
2475 2476 2477
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Xend version does not support modifying "
                             "persistent config"));
2478 2479
            return -1;
        }
2480
        /* Xen only supports modifying both live and persistent config if
2481 2482
         * xendConfigVersion >= 3
         */
2483
        if (priv->xendConfigVersion >= XEND_CONFIG_VERSION_3_0_4 &&
2484 2485
            (flags != (VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                       VIR_DOMAIN_DEVICE_MODIFY_CONFIG))) {
2486 2487 2488
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Xend only supports modifying both live and "
                             "persistent config"));
2489 2490 2491
            return -1;
        }
    }
2492

2493 2494 2495
    if (!(def = xenDaemonDomainFetch(conn,
                                     minidef->id,
                                     minidef->name,
2496 2497 2498
                                     NULL)))
        goto cleanup;

2499 2500
    if (!(dev = virDomainDeviceDefParse(xml, def, priv->caps, priv->xmlopt,
                                        VIR_DOMAIN_XML_INACTIVE)))
2501 2502
        goto cleanup;

2503
    if (virDomainXMLDevID(conn, minidef, dev, class, ref, sizeof(ref)))
2504 2505
        goto cleanup;

2506 2507 2508
    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ß 已提交
2509
            if (xenFormatSxprOnePCI(dev->data.hostdev, &buf, 1) < 0)
2510 2511
                goto cleanup;
        } else {
2512 2513
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("unsupported device type"));
2514 2515 2516
            goto cleanup;
        }
        xendev = virBufferContentAndReset(&buf);
2517
        ret = xend_op(conn, minidef->name, "op", "device_configure",
2518 2519 2520 2521
                      "config", xendev, "dev", ref, NULL);
        VIR_FREE(xendev);
    }
    else {
2522
        ret = xend_op(conn, minidef->name, "op", "device_destroy",
2523 2524 2525
                      "type", class, "dev", ref, "force", "0", "rm_cfg", "1",
                      NULL);
    }
2526 2527 2528 2529 2530 2531

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

    return ret;
2532
}
2533

2534
int
2535 2536 2537
xenDaemonDomainGetAutostart(virConnectPtr conn,
                            virDomainDefPtr def,
                            int *autostart)
2538 2539 2540 2541
{
    struct sexpr *root;
    const char *tmp;

2542
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
2543
    if (root == NULL) {
2544 2545
        virReportError(VIR_ERR_XEN_CALL,
                       "%s", _("xenDaemonGetAutostart failed to find this domain"));
2546
        return -1;
2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560
    }

    *autostart = 0;

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

    sexpr_free(root);
    return 0;
}

int
2561 2562 2563
xenDaemonDomainSetAutostart(virConnectPtr conn,
                            virDomainDefPtr def,
                            int autostart)
2564 2565
{
    struct sexpr *root, *autonode;
2566 2567
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    char *content = NULL;
2568 2569
    int ret = -1;

2570
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
2571
    if (root == NULL) {
2572 2573
        virReportError(VIR_ERR_XEN_CALL,
                       "%s", _("xenDaemonSetAutostart failed to find this domain"));
2574
        return -1;
2575 2576
    }

2577 2578 2579 2580
    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);
2581
        if (!val || (!STREQ(val, "ignore") && !STREQ(val, "start"))) {
2582 2583
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("unexpected value from on_xend_start"));
2584 2585 2586
            goto error;
        }

2587
        /* Change the autostart value in place, then define the new sexpr */
2588
        VIR_FREE(autonode->u.s.car->u.value);
2589 2590
        if (VIR_STRDUP(autonode->u.s.car->u.value,
                       autostart ? "start" : "ignore") < 0)
2591 2592
            goto error;

2593
        if (sexpr2string(root, &buffer) < 0) {
2594 2595
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("sexpr2string failed"));
2596 2597
            goto error;
        }
2598 2599 2600 2601 2602 2603 2604 2605

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

        content = virBufferContentAndReset(&buffer);

2606
        if (xend_op(conn, "", "op", "new", "config", content, NULL) != 0) {
2607 2608
            virReportError(VIR_ERR_XEN_CALL,
                           "%s", _("Failed to redefine sexpr"));
2609 2610 2611
            goto error;
        }
    } else {
2612 2613
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("on_xend_start not present in sexpr"));
2614 2615 2616 2617 2618
        goto error;
    }

    ret = 0;
  error:
2619 2620
    virBufferFreeAndReset(&buffer);
    VIR_FREE(content);
2621 2622 2623
    sexpr_free(root);
    return ret;
}
2624

2625
int
2626
xenDaemonDomainMigratePrepare(virConnectPtr dconn ATTRIBUTE_UNUSED,
2627 2628 2629 2630 2631 2632 2633
                              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)
2634
{
E
Eric Blake 已提交
2635 2636
    virCheckFlags(XEN_MIGRATION_FLAGS, -1);

2637 2638 2639 2640 2641
    /* 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) {
2642
        *uri_out = virGetHostname();
2643
        if (*uri_out == NULL)
2644 2645 2646 2647 2648 2649 2650
            return -1;
    }

    return 0;
}

int
2651 2652
xenDaemonDomainMigratePerform(virConnectPtr conn,
                              virDomainDefPtr def,
2653 2654 2655 2656 2657 2658
                              const char *cookie ATTRIBUTE_UNUSED,
                              int cookielen ATTRIBUTE_UNUSED,
                              const char *uri,
                              unsigned long flags,
                              const char *dname,
                              unsigned long bandwidth)
2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669
{
    /* 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;

2670 2671
    int undefined_source = 0;

E
Eric Blake 已提交
2672 2673
    virCheckFlags(XEN_MIGRATION_FLAGS, -1);

2674 2675
    /* Xen doesn't support renaming domains during migration. */
    if (dname) {
2676 2677 2678
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("xenDaemonDomainMigrate: Xen does not support"
                               " renaming domains during migration"));
2679 2680 2681 2682 2683 2684 2685
        return -1;
    }

    /* Xen (at least up to 3.1.0) takes a resource parameter but
     * ignores it.
     */
    if (bandwidth) {
2686 2687 2688
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("xenDaemonDomainMigrate: Xen does not support"
                               " bandwidth limits during migration"));
2689 2690 2691
        return -1;
    }

2692 2693 2694
    /*
     * Check the flags.
     */
2695
    if ((flags & VIR_MIGRATE_LIVE)) {
2696
        strcpy(live, "1");
2697 2698
        flags &= ~VIR_MIGRATE_LIVE;
    }
2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709

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

2710 2711 2712 2713
    /* This is buggy in Xend, but could be supported in principle.  Give
     * a nice error message.
     */
    if (flags & VIR_MIGRATE_PAUSED) {
2714 2715
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("xenDaemonDomainMigrate: xend cannot migrate paused domains"));
2716 2717 2718
        return -1;
    }

2719 2720
    /* XXX we could easily do tunnelled & peer2peer migration too
       if we want to. support these... */
2721
    if (flags != 0) {
2722 2723
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("xenDaemonDomainMigrate: unsupported flag"));
2724 2725 2726 2727 2728 2729 2730 2731
        return -1;
    }

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

2737
        if (uriptr->scheme && STRCASENEQ(uriptr->scheme, "xenmigr")) {
2738 2739 2740
            virReportError(VIR_ERR_INVALID_ARG,
                           "%s", _("xenDaemonDomainMigrate: only xenmigr://"
                                   " migrations are supported by Xen"));
2741
            virURIFree(uriptr);
2742 2743 2744
            return -1;
        }
        if (!uriptr->server) {
2745 2746 2747
            virReportError(VIR_ERR_INVALID_ARG,
                           "%s", _("xenDaemonDomainMigrate: a hostname must be"
                                   " specified in the URI"));
2748
            virURIFree(uriptr);
2749 2750
            return -1;
        }
2751
        if (VIR_STRDUP(hostname, uriptr->server) < 0) {
2752
            virURIFree(uriptr);
2753 2754 2755
            return -1;
        }
        if (uriptr->port)
2756 2757
            snprintf(port, sizeof(port), "%d", uriptr->port);
        virURIFree(uriptr);
2758
    }
2759
    else if ((p = strrchr(uri, ':')) != NULL) { /* "hostname:port" */
2760 2761
        int port_nr, n;

2762
        if (virStrToLong_i(p+1, NULL, 10, &port_nr) < 0) {
2763 2764
            virReportError(VIR_ERR_INVALID_ARG,
                           "%s", _("xenDaemonDomainMigrate: invalid port number"));
2765 2766
            return -1;
        }
2767
        snprintf(port, sizeof(port), "%d", port_nr);
2768 2769 2770

        /* Get the hostname. */
        n = p - uri; /* n = Length of hostname in bytes. */
2771
        if (VIR_STRDUP(hostname, uri) < 0)
2772 2773 2774 2775
            return -1;
        hostname[n] = '\0';
    }
    else {                      /* "hostname" (or IP address) */
2776
        if (VIR_STRDUP(hostname, uri) < 0)
2777 2778 2779
            return -1;
    }

2780
    VIR_DEBUG("hostname = %s, port = %s", hostname, port);
2781

J
Jim Fehlig 已提交
2782 2783 2784 2785 2786 2787
    /* 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.
     */
2788
    ret = xend_op(conn, def->name,
2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
                  "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);
2799

2800
    if (ret == 0 && undefined_source)
2801
        xenDaemonDomainUndefine(conn, def);
2802

2803
    VIR_DEBUG("migration done");
2804 2805 2806 2807

    return ret;
}

2808 2809
int
xenDaemonDomainDefineXML(virConnectPtr conn, virDomainDefPtr def)
2810
{
2811
    int ret = -1;
2812
    char *sexpr;
2813
    xenUnifiedPrivatePtr priv = conn->privateData;
2814

M
Markus Groß 已提交
2815
    if (!(sexpr = xenFormatSxpr(conn, def, priv->xendConfigVersion))) {
2816 2817
        virReportError(VIR_ERR_XML_ERROR,
                       "%s", _("failed to build sexpr"));
2818
        goto cleanup;
2819 2820
    }

2821
    ret = xend_op(conn, "", "op", "new", "config", sexpr, NULL);
2822
    VIR_FREE(sexpr);
2823
    if (ret != 0) {
2824 2825
        virReportError(VIR_ERR_XEN_CALL,
                       _("Failed to create inactive domain %s"), def->name);
2826
        goto cleanup;
2827 2828
    }

2829
    ret = 0;
2830

2831 2832
cleanup:
    return ret;
2833
}
2834

2835
int
2836 2837
xenDaemonDomainCreate(virConnectPtr conn,
                      virDomainDefPtr def)
2838
{
2839
    int ret;
2840

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

2843
    if (ret == 0) {
2844 2845
        int id = xenDaemonDomainLookupByName_ids(conn, def->name,
                                                 def->uuid);
2846
        if (id > 0)
2847
            def->id = id;
2848
    }
2849

2850
    return ret;
2851 2852
}

2853
int
2854
xenDaemonDomainUndefine(virConnectPtr conn, virDomainDefPtr def)
2855
{
2856
    return xend_op(conn, def->name, "op", "delete", NULL);
2857 2858 2859 2860 2861 2862 2863 2864 2865 2866
}

/**
 * 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
 */
2867
int
2868 2869 2870 2871 2872
xenDaemonNumOfDefinedDomains(virConnectPtr conn)
{
    struct sexpr *root = NULL;
    int ret = -1;
    struct sexpr *_for_i, *node;
2873

2874 2875 2876 2877 2878 2879
    root = sexpr_get(conn, "/xend/domain?state=halted");
    if (root == NULL)
        goto error;

    ret = 0;

2880
    /* coverity[copy_paste_error] */
2881 2882
    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) {
2883 2884 2885 2886 2887 2888
        if (node->kind != SEXPR_VALUE)
            continue;
        ret++;
    }

error:
2889
    sexpr_free(root);
2890
    return ret;
2891 2892
}

2893
int
2894 2895 2896 2897
xenDaemonListDefinedDomains(virConnectPtr conn,
                            char **const names,
                            int maxnames)
{
2898
    struct sexpr *root = NULL;
2899
    size_t i;
2900
    int ret = 0;
2901
    struct sexpr *_for_i, *node;
2902

2903
    if (maxnames == 0)
2904
        return 0;
2905

2906 2907 2908 2909
    root = sexpr_get(conn, "/xend/domain?state=halted");
    if (root == NULL)
        goto error;

2910
    /* coverity[copy_paste_error] */
2911 2912
    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) {
2913 2914 2915
        if (node->kind != SEXPR_VALUE)
            continue;

2916
        if (VIR_STRDUP(names[ret++], node->u.value) < 0)
2917 2918
            goto error;

2919 2920 2921 2922
        if (ret >= maxnames)
            break;
    }

2923 2924
cleanup:
    sexpr_free(root);
2925
    return ret;
2926

2927
error:
2928
    for (i = 0; i < ret; ++i)
2929 2930
        VIR_FREE(names[i]);

2931
    ret = -1;
2932
    goto cleanup;
2933 2934
}

2935 2936
/**
 * xenDaemonGetSchedulerType:
2937
 * @conn: the hypervisor connection
2938 2939 2940 2941 2942 2943 2944
 * @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
 */
2945
char *
2946 2947
xenDaemonGetSchedulerType(virConnectPtr conn,
                          int *nparams)
2948
{
2949
    xenUnifiedPrivatePtr priv = conn->privateData;
2950 2951 2952 2953 2954
    struct sexpr *root;
    const char *ret = NULL;
    char *schedulertype = NULL;

    /* Support only xendConfigVersion >=4 */
2955
    if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_1_0) {
2956 2957
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("unsupported in xendConfigVersion < 4"));
2958 2959 2960
        return NULL;
    }

2961
    root = sexpr_get(conn, "/xend/node/");
2962 2963 2964 2965 2966 2967
    if (root == NULL)
        return NULL;

    /* get xen_scheduler from xend/node */
    ret = sexpr_node(root, "node/xen_scheduler");
    if (ret == NULL){
2968 2969
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("node information incomplete, missing scheduler name"));
2970 2971
        goto error;
    }
2972
    if (STREQ(ret, "credit")) {
2973
        if (VIR_STRDUP(schedulertype, "credit") < 0)
2974
            goto error;
2975 2976
        if (nparams)
            *nparams = XEN_SCHED_CRED_NPARAM;
2977
    } else if (STREQ(ret, "sedf")) {
2978
        if (VIR_STRDUP(schedulertype, "sedf") < 0)
2979
            goto error;
2980 2981
        if (nparams)
            *nparams = XEN_SCHED_SEDF_NPARAM;
2982
    } else {
2983
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Unknown scheduler"));
2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994
        goto error;
    }

error:
    sexpr_free(root);
    return schedulertype;

}

/**
 * xenDaemonGetSchedulerParameters:
2995 2996
 * @conn: the hypervisor connection
 * @def: domain configuration
2997 2998 2999 3000 3001 3002 3003 3004 3005
 * @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
 */
3006
int
3007 3008
xenDaemonGetSchedulerParameters(virConnectPtr conn,
                                virDomainDefPtr def,
3009 3010
                                virTypedParameterPtr params,
                                int *nparams)
3011
{
3012
    xenUnifiedPrivatePtr priv = conn->privateData;
3013 3014 3015 3016 3017 3018
    struct sexpr *root;
    char *sched_type = NULL;
    int sched_nparam = 0;
    int ret = -1;

    /* Support only xendConfigVersion >=4 */
3019
    if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_1_0) {
3020 3021
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("unsupported in xendConfigVersion < 4"));
3022
        return -1;
3023 3024 3025
    }

    /* look up the information by domain name */
3026
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
3027
    if (root == NULL)
3028
        return -1;
3029 3030

    /* get the scheduler type */
3031
    sched_type = xenDaemonGetSchedulerType(conn, &sched_nparam);
3032
    if (sched_type == NULL) {
3033 3034
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("Failed to get a scheduler name"));
3035 3036 3037 3038 3039
        goto error;
    }

    switch (sched_nparam){
        case XEN_SCHED_SEDF_NPARAM:
3040
            if (*nparams < XEN_SCHED_SEDF_NPARAM) {
3041 3042
                virReportError(VIR_ERR_INVALID_ARG,
                               "%s", _("Invalid parameter count"));
3043 3044 3045
                goto error;
            }

3046 3047 3048 3049 3050 3051
            /* 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) {
3052 3053
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               "%s", _("domain information incomplete, missing cpu_weight"));
3054 3055 3056
                goto error;
            }
            if (sexpr_node(root, "domain/cpu_cap") == NULL) {
3057 3058
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               "%s", _("domain information incomplete, missing cpu_cap"));
3059 3060 3061
                goto error;
            }

3062 3063
            if (virStrcpyStatic(params[0].field,
                                VIR_DOMAIN_SCHEDULER_WEIGHT) == NULL) {
3064 3065 3066
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Weight %s too big for destination"),
                               VIR_DOMAIN_SCHEDULER_WEIGHT);
C
Chris Lalancette 已提交
3067 3068
                goto error;
            }
3069
            params[0].type = VIR_TYPED_PARAM_UINT;
3070 3071
            params[0].value.ui = sexpr_int(root, "domain/cpu_weight");

3072 3073 3074
            if (*nparams > 1) {
                if (virStrcpyStatic(params[1].field,
                                    VIR_DOMAIN_SCHEDULER_CAP) == NULL) {
3075 3076 3077
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Cap %s too big for destination"),
                                   VIR_DOMAIN_SCHEDULER_CAP);
3078 3079 3080 3081
                    goto error;
                }
                params[1].type = VIR_TYPED_PARAM_UINT;
                params[1].value.ui = sexpr_int(root, "domain/cpu_cap");
C
Chris Lalancette 已提交
3082
            }
3083 3084 3085

            if (*nparams > XEN_SCHED_CRED_NPARAM)
                *nparams = XEN_SCHED_CRED_NPARAM;
3086 3087 3088
            ret = 0;
            break;
        default:
3089
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Unknown scheduler"));
3090 3091 3092 3093 3094
            goto error;
    }

error:
    sexpr_free(root);
3095
    VIR_FREE(sched_type);
3096
    return ret;
3097 3098 3099 3100
}

/**
 * xenDaemonSetSchedulerParameters:
3101 3102
 * @conn: the hypervisor connection
 * @def: domain configuration
3103 3104 3105 3106 3107 3108 3109
 * @params: pointer to scheduler parameters
 * @nparams: a number of scheduler setting parameters
 *
 * Set the scheduler parameters
 *
 * Returns 0 or -1 in case of failure
 */
3110
int
3111 3112
xenDaemonSetSchedulerParameters(virConnectPtr conn,
                                virDomainDefPtr def,
3113 3114
                                virTypedParameterPtr params,
                                int nparams)
3115
{
3116
    xenUnifiedPrivatePtr priv = conn->privateData;
3117 3118
    struct sexpr *root;
    char *sched_type = NULL;
3119
    size_t i;
3120 3121 3122 3123
    int sched_nparam = 0;
    int ret = -1;

    /* Support only xendConfigVersion >=4 and active domains */
3124
    if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_1_0) {
3125 3126
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("unsupported in xendConfigVersion < 4"));
3127
        return -1;
3128 3129 3130
    }

    /* look up the information by domain name */
3131
    root = sexpr_get(conn, "/xend/domain/%s?detail=1", def->name);
3132
    if (root == NULL)
3133
        return -1;
3134 3135

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

3190
            ret = xend_op(conn, def->name, "op",
3191 3192 3193 3194 3195
                          "domain_sched_credit_set", "weight", buf_weight,
                          "cap", buf_cap, NULL);
            break;
        }
        default:
3196
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Unknown scheduler"));
3197 3198 3199 3200 3201
            goto error;
    }

error:
    sexpr_free(root);
3202
    VIR_FREE(sched_type);
3203
    return ret;
3204 3205
}

R
Richard W.M. Jones 已提交
3206 3207
/**
 * xenDaemonDomainBlockPeek:
3208 3209
 * @conn: the hypervisor connection
 * @minidef: minimal domain configuration
R
Richard W.M. Jones 已提交
3210 3211 3212 3213 3214
 * @path: path to the file or device
 * @offset: offset
 * @size: size
 * @buffer: return buffer
 *
3215
 * Returns 0 if successful, -1 if error
R
Richard W.M. Jones 已提交
3216 3217
 */
int
3218 3219
xenDaemonDomainBlockPeek(virConnectPtr conn,
                         virDomainDefPtr minidef,
3220 3221 3222
                         const char *path,
                         unsigned long long offset,
                         size_t size,
3223
                         void *buffer)
R
Richard W.M. Jones 已提交
3224
{
3225
    xenUnifiedPrivatePtr priv = conn->privateData;
3226 3227
    struct sexpr *root = NULL;
    int fd = -1, ret = -1;
3228
    virDomainDefPtr def = NULL;
3229 3230 3231
    int id;
    char * tty;
    int vncport;
3232
    const char *actual;
R
Richard W.M. Jones 已提交
3233 3234

    /* Security check: The path must correspond to a block device. */
3235 3236 3237 3238 3239 3240
    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 已提交
3241 3242
    else {
        /* This call always fails for dom0. */
3243 3244
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domainBlockPeek is not supported for dom0"));
R
Richard W.M. Jones 已提交
3245 3246 3247 3248
        return -1;
    }

    if (!root) {
3249
        virReportError(VIR_ERR_XEN_CALL, __FUNCTION__);
R
Richard W.M. Jones 已提交
3250 3251 3252
        return -1;
    }

3253 3254
    if (xenGetDomIdFromSxpr(root, priv->xendConfigVersion, &id) < 0)
        goto cleanup;
3255
    xenUnifiedLock(priv);
3256 3257
    tty = xenStoreDomainGetConsolePath(conn, id);
    vncport = xenStoreDomainGetVNCPort(conn, id);
3258 3259
    xenUnifiedUnlock(priv);

M
Markus Groß 已提交
3260 3261
    if (!(def = xenParseSxpr(root, priv->xendConfigVersion, NULL, tty,
                             vncport)))
3262
        goto cleanup;
R
Richard W.M. Jones 已提交
3263

3264
    if (!(actual = virDomainDiskPathByName(def, path))) {
3265 3266
        virReportError(VIR_ERR_INVALID_ARG,
                       _("%s: invalid path"), path);
3267
        goto cleanup;
R
Richard W.M. Jones 已提交
3268
    }
3269
    path = actual;
R
Richard W.M. Jones 已提交
3270 3271

    /* The path is correct, now try to open it and get its size. */
3272
    fd = open(path, O_RDONLY);
3273
    if (fd == -1) {
3274
        virReportSystemError(errno,
3275 3276
                             _("failed to open for reading: %s"),
                             path);
3277
        goto cleanup;
R
Richard W.M. Jones 已提交
3278 3279 3280 3281 3282 3283
    }

    /* Seek and read. */
    /* NB. Because we configure with AC_SYS_LARGEFILE, off_t should
     * be 64 bits on all platforms.
     */
3284 3285
    if (lseek(fd, offset, SEEK_SET) == (off_t) -1 ||
        saferead(fd, buffer, size) == (ssize_t) -1) {
3286
        virReportSystemError(errno,
3287 3288
                             _("failed to lseek or read from file: %s"),
                             path);
3289
        goto cleanup;
R
Richard W.M. Jones 已提交
3290 3291 3292
    }

    ret = 0;
3293
 cleanup:
3294
    VIR_FORCE_CLOSE(fd);
3295 3296
    sexpr_free(root);
    virDomainDefFree(def);
R
Richard W.M. Jones 已提交
3297 3298 3299
    return ret;
}

3300 3301 3302

/**
 * virDomainXMLDevID:
3303 3304
 * @conn: the hypervisor connection
 * @minidef: minimal domain configuration
3305 3306 3307 3308 3309 3310 3311 3312
 * @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.
3313 3314
 *  - if pci, get BDF from description, scan XenStore and
 *    copy in ref the corresponding dev number.
3315 3316 3317 3318
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
static int
3319 3320
virDomainXMLDevID(virConnectPtr conn,
                  virDomainDefPtr def,
3321 3322 3323 3324 3325
                  virDomainDeviceDefPtr dev,
                  char *class,
                  char *ref,
                  int ref_len)
{
3326
    xenUnifiedPrivatePtr priv = conn->privateData;
3327
    char *xref;
C
Chris Lalancette 已提交
3328
    char *tmp;
3329 3330

    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
3331 3332 3333
        if (dev->data.disk->driverName &&
            STREQ(dev->data.disk->driverName, "tap"))
            strcpy(class, "tap");
J
Jim Fehlig 已提交
3334 3335 3336
        else if (dev->data.disk->driverName &&
            STREQ(dev->data.disk->driverName, "tap2"))
            strcpy(class, "tap2");
3337 3338 3339
        else
            strcpy(class, "vbd");

3340 3341
        if (dev->data.disk->dst == NULL)
            return -1;
D
Daniel P. Berrange 已提交
3342
        xenUnifiedLock(priv);
3343
        xref = xenStoreDomainGetDiskID(conn, def->id,
3344
                                       dev->data.disk->dst);
D
Daniel P. Berrange 已提交
3345
        xenUnifiedUnlock(priv);
3346 3347 3348
        if (xref == NULL)
            return -1;

C
Chris Lalancette 已提交
3349
        tmp = virStrcpy(ref, xref, ref_len);
3350
        VIR_FREE(xref);
C
Chris Lalancette 已提交
3351 3352
        if (tmp == NULL)
            return -1;
3353
    } else if (dev->type == VIR_DOMAIN_DEVICE_NET) {
3354
        char mac[VIR_MAC_STRING_BUFLEN];
3355 3356
        virDomainNetDefPtr netdef = dev->data.net;
        virMacAddrFormat(&netdef->mac, mac);
3357 3358 3359

        strcpy(class, "vif");

D
Daniel P. Berrange 已提交
3360
        xenUnifiedLock(priv);
3361
        xref = xenStoreDomainGetNetworkID(conn, def->id, mac);
D
Daniel P. Berrange 已提交
3362
        xenUnifiedUnlock(priv);
3363 3364 3365
        if (xref == NULL)
            return -1;

C
Chris Lalancette 已提交
3366
        tmp = virStrcpy(ref, xref, ref_len);
3367
        VIR_FREE(xref);
C
Chris Lalancette 已提交
3368 3369
        if (tmp == NULL)
            return -1;
3370 3371 3372
    } 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) {
3373
        char *bdf;
3374
        virDomainHostdevDefPtr hostdef = dev->data.hostdev;
3375 3376

        if (virAsprintf(&bdf, "%04x:%02x:%02x.%0x",
3377 3378 3379
                        hostdef->source.subsys.u.pci.addr.domain,
                        hostdef->source.subsys.u.pci.addr.bus,
                        hostdef->source.subsys.u.pci.addr.slot,
3380
                        hostdef->source.subsys.u.pci.addr.function) < 0)
3381 3382 3383 3384 3385
            return -1;

        strcpy(class, "pci");

        xenUnifiedLock(priv);
3386
        xref = xenStoreDomainGetPCIID(conn, def->id, bdf);
3387 3388 3389 3390 3391 3392 3393 3394 3395
        xenUnifiedUnlock(priv);
        VIR_FREE(bdf);
        if (xref == NULL)
            return -1;

        tmp = virStrcpy(ref, xref, ref_len);
        VIR_FREE(xref);
        if (tmp == NULL)
            return -1;
3396
    } else {
3397 3398
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("hotplug of device type not supported"));
3399 3400 3401 3402 3403
        return -1;
    }

    return 0;
}