xm_internal.c 85.6 KB
Newer Older
1 2 3
/*
 * xm_internal.h: helper routines for dealing with inactive domains
 *
4 5
 * Copyright (C) 2006-2007 Red Hat
 * Copyright (C) 2006 Daniel P. Berrange
6
 *
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 * 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
22 23 24
 *
 */

25
#ifdef WITH_XEN
26
#include <config.h>
27

28 29 30
#include <dirent.h>
#include <time.h>
#include <sys/stat.h>
31
#include <limits.h>
32 33
#include <string.h>
#include <errno.h>
34 35 36 37 38 39 40 41 42

#include <unistd.h>
#include <stdint.h>
#include <xen/dom0_ops.h>

#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>

43 44 45
#ifndef NAME_MAX
#define	NAME_MAX	255
#endif
46

47
#include "xen_unified.h"
48 49 50 51 52
#include "xm_internal.h"
#include "xend_internal.h"
#include "hash.h"
#include "internal.h"
#include "xml.h"
53
#include "buf.h"
54
#include "uuid.h"
55
#include "util.h"
56
#include "memory.h"
57

58 59 60 61 62
/* The true Xen limit varies but so far is always way
   less than 1024, which is the Linux kernel limit according
   to sched.h, so we'll match that for now */
#define XEN_MAX_PHYSICAL_CPU 1024

63 64 65
static int xenXMConfigSetString(virConfPtr conf, const char *setting,
                                const char *str);

66 67 68 69
typedef struct xenXMConfCache *xenXMConfCachePtr;
typedef struct xenXMConfCache {
    time_t refreshedAt;
    char filename[PATH_MAX];
70
    virDomainDefPtr def;
71 72 73
} xenXMConfCache;

static char configDir[PATH_MAX];
74
/* Config file name to config object */
75
static virHashTablePtr configCache = NULL;
76
/* Name to config file name */
77
static virHashTablePtr nameConfigMap = NULL;
78 79 80
static int nconnections = 0;
static time_t lastRefresh = 0;

81
char * xenXMAutoAssignMac(void);
82 83
static int xenXMDomainAttachDevice(virDomainPtr domain, const char *xml);
static int xenXMDomainDetachDevice(virDomainPtr domain, const char *xml);
84

85 86 87 88 89 90 91
#define XM_REFRESH_INTERVAL 10

#define XM_CONFIG_DIR "/etc/xen"
#define XM_EXAMPLE_PREFIX "xmexample"
#define XEND_CONFIG_FILE "xend-config.sxp"
#define XEND_PCI_CONFIG_PREFIX "xend-pci-"
#define QEMU_IF_SCRIPT "qemu-ifup"
92
#define XM_XML_ERROR "Invalid xml"
93

94
struct xenUnifiedDriver xenXMDriver = {
95 96 97
    xenXMOpen, /* open */
    xenXMClose, /* close */
    NULL, /* version */
98 99
    NULL, /* hostname */
    NULL, /* URI */
100
    NULL, /* nodeGetInfo */
101
    NULL, /* getCapabilities */
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
    NULL, /* listDomains */
    NULL, /* numOfDomains */
    NULL, /* domainCreateLinux */
    NULL, /* domainSuspend */
    NULL, /* domainResume */
    NULL, /* domainShutdown */
    NULL, /* domainReboot */
    NULL, /* domainDestroy */
    NULL, /* domainGetOSType */
    xenXMDomainGetMaxMemory, /* domainGetMaxMemory */
    xenXMDomainSetMaxMemory, /* domainSetMaxMemory */
    xenXMDomainSetMemory, /* domainMaxMemory */
    xenXMDomainGetInfo, /* domainGetInfo */
    NULL, /* domainSave */
    NULL, /* domainRestore */
D
Daniel Veillard 已提交
117
    NULL, /* domainCoreDump */
118
    xenXMDomainSetVcpus, /* domainSetVcpus */
119
    xenXMDomainPinVcpu, /* domainPinVcpu */
120
    NULL, /* domainGetVcpus */
121
    NULL, /* domainGetMaxVcpus */
122 123 124 125 126
    xenXMListDefinedDomains, /* listDefinedDomains */
    xenXMNumOfDefinedDomains, /* numOfDefinedDomains */
    xenXMDomainCreate, /* domainCreate */
    xenXMDomainDefineXML, /* domainDefineXML */
    xenXMDomainUndefine, /* domainUndefine */
127 128
    xenXMDomainAttachDevice, /* domainAttachDevice */
    xenXMDomainDetachDevice, /* domainDetachDevice */
129 130
    NULL, /* domainGetAutostart */
    NULL, /* domainSetAutostart */
131 132 133
    NULL, /* domainGetSchedulerType */
    NULL, /* domainGetSchedulerParameters */
    NULL, /* domainSetSchedulerParameters */
134 135 136 137 138 139 140 141 142 143 144
};

static void
xenXMError(virConnectPtr conn, virErrorNumber error, const char *info)
{
    const char *errmsg;

    if (error == VIR_ERR_OK)
        return;

    errmsg = __virErrorMsg(error, info);
145
    __virRaiseError(conn, NULL, NULL, VIR_FROM_XENXM, error, VIR_ERR_ERROR,
146 147 148
                    errmsg, info, NULL, 0, 0, errmsg, info);
}

149 150
int
xenXMInit (void)
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
{
    char *envConfigDir;
    int safeMode = 0;

    /* Disable use of env variable if running setuid */
    if ((geteuid() != getuid()) ||
        (getegid() != getgid()))
        safeMode = 1;

    if (!safeMode &&
        (envConfigDir = getenv("LIBVIRT_XM_CONFIG_DIR")) != NULL) {
        strncpy(configDir, envConfigDir, PATH_MAX-1);
        configDir[PATH_MAX-1] = '\0';
    } else {
        strcpy(configDir, XM_CONFIG_DIR);
    }
167 168

    return 0;
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
}


/* Convenience method to grab a int from the config file object */
static int xenXMConfigGetInt(virConfPtr conf, const char *name, long *value) {
    virConfValuePtr val;
    if (!value || !name || !conf)
        return (-1);

    if (!(val = virConfGetValue(conf, name))) {
        return (-1);
    }

    if (val->type == VIR_CONF_LONG) {
        *value = val->l;
    } else if (val->type == VIR_CONF_STRING) {
        char *ret;
        if (!val->str)
            return (-1);
        *value = strtol(val->str, &ret, 10);
        if (ret == val->str)
            return (-1);
    } else {
        return (-1);
    }
    return (0);
}


/* Convenience method to grab a string from the config file object */
static int xenXMConfigGetString(virConfPtr conf, const char *name, const char **value) {
    virConfValuePtr val;
    if (!value || !name || !conf)
        return (-1);
    *value = NULL;
    if (!(val = virConfGetValue(conf, name))) {
        return (-1);
    }
    if (val->type != VIR_CONF_STRING)
        return (-1);
    if (!val->str)
        return (-1);
    *value = val->str;
    return (0);
}

/* Convenience method to grab a string UUID from the config file object */
static int xenXMConfigGetUUID(virConfPtr conf, const char *name, unsigned char *uuid) {
    virConfValuePtr val;
    if (!uuid || !name || !conf)
        return (-1);
    if (!(val = virConfGetValue(conf, name))) {
        return (-1);
    }

    if (val->type != VIR_CONF_STRING)
        return (-1);
    if (!val->str)
        return (-1);

229
    if (virUUIDParse(val->str, uuid) < 0)
230 231 232 233 234 235 236 237 238
        return (-1);

    return (0);
}


/* Release memory associated with a cached config object */
static void xenXMConfigFree(void *payload, const char *key ATTRIBUTE_UNUSED) {
    xenXMConfCachePtr entry = (xenXMConfCachePtr)payload;
239
    virDomainDefFree(entry->def);
240
    VIR_FREE(entry);
241 242 243
}


244 245 246 247 248
/* Remove any configs which were not refreshed recently */
static int xenXMConfigReaper(const void *payload, const char *key ATTRIBUTE_UNUSED, const void *data) {
    time_t now = *(const time_t *)data;
    xenXMConfCachePtr entry = (xenXMConfCachePtr)payload;

249 250
    /* We're going to purge this config file, so check if it
       is currently mapped as owner of a named domain. */
251
    if (entry->refreshedAt != now) {
252 253 254 255
        const char *olddomname = entry->def->name;
        char *nameowner = (char *)virHashLookup(nameConfigMap, olddomname);
        if (nameowner && STREQ(nameowner, key)) {
            virHashRemoveEntry(nameConfigMap, olddomname, NULL);
256 257 258 259 260 261
        }
        return (1);
    }
    return (0);
}

262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290

static virDomainDefPtr
xenXMConfigReadFile(virConnectPtr conn, const char *filename) {
    virConfPtr conf;
    virDomainDefPtr def;

    if (!(conf = virConfReadFile(filename)))
        return NULL;

    def = xenXMDomainConfigParse(conn, conf);
    virConfFree(conf);

    return def;
}

static int
xenXMConfigSaveFile(virConnectPtr conn, const char *filename, virDomainDefPtr def) {
    virConfPtr conf;
    int ret;

    if (!(conf = xenXMDomainConfigFormat(conn, def)))
        return -1;

    ret = virConfWriteFile(filename, conf);
    virConfFree(conf);
    return ret;
}


291 292 293 294 295
/* This method is called by various methods to scan /etc/xen
   (or whatever directory was set by  LIBVIRT_XM_CONFIG_DIR
   environment variable) and process any domain configs. It
   has rate-limited so never rescans more frequently than
   once every X seconds */
296
static int xenXMConfigCacheRefresh (virConnectPtr conn) {
297 298 299 300 301 302
    DIR *dh;
    struct dirent *ent;
    time_t now = time(NULL);
    int ret = -1;

    if (now == ((time_t)-1)) {
303
        xenXMError (conn, VIR_ERR_SYSTEM_ERROR, strerror (errno));
304 305 306 307 308 309 310 311 312 313 314
        return (-1);
    }

    /* Rate limit re-scans */
    if ((now - lastRefresh) < XM_REFRESH_INTERVAL)
        return (0);

    lastRefresh = now;

    /* Process the files in the config dir */
    if (!(dh = opendir(configDir))) {
315
        xenXMError (conn, VIR_ERR_SYSTEM_ERROR, strerror (errno));
316 317 318 319 320 321 322 323 324 325 326 327 328 329
        return (-1);
    }

    while ((ent = readdir(dh))) {
        xenXMConfCachePtr entry;
        struct stat st;
        int newborn = 0;
        char path[PATH_MAX];

        /*
         * Skip a bunch of crufty files that clearly aren't config files
         */

        /* Like 'dot' files... */
330
        if (STRPREFIX(ent->d_name, "."))
331 332
            continue;
        /* ...and the XenD server config file */
333
        if (STRPREFIX(ent->d_name, XEND_CONFIG_FILE))
334 335
            continue;
        /* ...and random PCI config cruft */
336
        if (STRPREFIX(ent->d_name, XEND_PCI_CONFIG_PREFIX))
337 338
            continue;
        /* ...and the example domain configs */
339
        if (STRPREFIX(ent->d_name, XM_EXAMPLE_PREFIX))
340 341
            continue;
        /* ...and the QEMU networking script */
342
        if (STRPREFIX(ent->d_name, QEMU_IF_SCRIPT))
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
            continue;

        /* ...and editor backups */
        if (ent->d_name[0] == '#')
            continue;
        if (ent->d_name[strlen(ent->d_name)-1] == '~')
            continue;

        /* Build the full file path */
        if ((strlen(configDir) + 1 + strlen(ent->d_name) + 1) > PATH_MAX)
            continue;
        strcpy(path, configDir);
        strcat(path, "/");
        strcat(path, ent->d_name);

        /* Skip anything which isn't a file (takes care of scripts/ subdir */
        if ((stat(path, &st) < 0) ||
            (!S_ISREG(st.st_mode))) {
            continue;
        }

        /* If we already have a matching entry and it is not
           modified, then carry on to next one*/
366
        if ((entry = virHashLookup(configCache, path))) {
367
            char *nameowner;
368

369 370 371 372 373
            if (entry->refreshedAt >= st.st_mtime) {
                entry->refreshedAt = now;
                continue;
            }

374 375
            /* If we currently own the name, then release it and
               re-acquire it later - just in case it was renamed */
376 377 378
            nameowner = (char *)virHashLookup(nameConfigMap, entry->def->name);
            if (nameowner && STREQ(nameowner, path)) {
                virHashRemoveEntry(nameConfigMap, entry->def->name, NULL);
379 380 381
            }

            /* Clear existing config entry which needs refresh */
382 383
            virDomainDefFree(entry->def);
            entry->def = NULL;
384 385
        } else { /* Completely new entry */
            newborn = 1;
386
            if (VIR_ALLOC(entry) < 0) {
387
                xenXMError (conn, VIR_ERR_NO_MEMORY, strerror (errno));
388 389 390 391 392 393
                goto cleanup;
            }
            memcpy(entry->filename, path, PATH_MAX);
        }
        entry->refreshedAt = now;

394 395
        if (!(entry->def = xenXMConfigReadFile(conn, entry->filename))) {
            if (!newborn)
396
                virHashRemoveEntry(configCache, path, NULL);
397
            VIR_FREE(entry);
398 399 400 401 402 403
            continue;
        }

        /* If its a completely new entry, it must be stuck into
           the cache (refresh'd entries are already registered) */
        if (newborn) {
404
            if (virHashAddEntry(configCache, entry->filename, entry) < 0) {
405
                virDomainDefFree(entry->def);
406
                VIR_FREE(entry);
407 408
                xenXMError (conn, VIR_ERR_INTERNAL_ERROR,
                            _("xenXMConfigCacheRefresh: virHashAddEntry"));
409 410 411
                goto cleanup;
            }
        }
412 413 414 415

        /* See if we need to map this config file in as the primary owner
         * of the domain in question
         */
416 417
        if (!virHashLookup(nameConfigMap, entry->def->name)) {
            if (virHashAddEntry(nameConfigMap, entry->def->name, entry->filename) < 0) {
418
                virHashRemoveEntry(configCache, ent->d_name, NULL);
419
                virDomainDefFree(entry->def);
420
                VIR_FREE(entry);
421 422
            }
        }
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
    }

    /* Reap all entries which were not changed, by comparing
       their refresh timestamp - the timestamp should match
       'now' if they were refreshed. If timestamp doesn't match
       then the config is no longer on disk */
    virHashRemoveSet(configCache, xenXMConfigReaper, xenXMConfigFree, (const void*) &now);
    ret = 0;

 cleanup:
    if (dh)
        closedir(dh);

    return (ret);
}


/*
 * Open a 'connection' to the config file directory ;-)
 * We just create a hash table to store config files in.
 * We only support a single directory, so repeated calls
 * to open all end up using the same cache of files
 */
446 447
int
xenXMOpen (virConnectPtr conn ATTRIBUTE_UNUSED,
448 449 450
           xmlURIPtr uri ATTRIBUTE_UNUSED,
           virConnectAuthPtr auth ATTRIBUTE_UNUSED,
           int flags ATTRIBUTE_UNUSED)
451
{
452
    if (configCache == NULL) {
453 454 455
        configCache = virHashCreate(50);
        if (!configCache)
            return (-1);
456 457 458 459 460 461
        nameConfigMap = virHashCreate(50);
        if (!nameConfigMap) {
            virHashFree(configCache, NULL);
            configCache = NULL;
            return (-1);
        }
462 463 464 465
        /* Force the cache to be reloaded next time that
         * xenXMConfigCacheRefresh is called.
         */
        lastRefresh = 0;
466 467 468 469 470 471 472 473 474 475 476
    }
    nconnections++;

    return (0);
}

/*
 * Free the config files in the cache if this is the
 * last connection
 */
int xenXMClose(virConnectPtr conn ATTRIBUTE_UNUSED) {
477 478
    nconnections--;
    if (nconnections <= 0) {
479 480
        virHashFree(nameConfigMap, NULL);
        nameConfigMap = NULL;
481 482 483 484 485 486 487 488
        virHashFree(configCache, xenXMConfigFree);
        configCache = NULL;
    }
    return (0);
}

/*
 * Since these are all offline domains, we only return info about
489
 * VCPUs and memory.
490 491
 */
int xenXMDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info) {
492
    const char *filename;
493 494 495 496 497 498 499
    xenXMConfCachePtr entry;
    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
        xenXMError((domain ? domain->conn : NULL), VIR_ERR_INVALID_ARG,
                   __FUNCTION__);
        return(-1);
    }

500
    if (domain->id != -1)
501 502
        return (-1);

503 504 505 506
    if (!(filename = virHashLookup(nameConfigMap, domain->name)))
        return (-1);

    if (!(entry = virHashLookup(configCache, filename)))
507 508 509
        return (-1);

    memset(info, 0, sizeof(virDomainInfo));
510 511 512
    info->maxMem = entry->def->maxmem;
    info->memory = entry->def->memory;
    info->nrVirtCpu = entry->def->vcpus;
513 514 515 516 517 518 519
    info->state = VIR_DOMAIN_SHUTOFF;
    info->cpuTime = 0;

    return (0);

}

520
#define MAX_VFB 1024
521 522 523 524
/*
 * Turn a config record into a lump of XML describing the
 * domain, suitable for later feeding for virDomainCreateLinux
 */
525 526
virDomainDefPtr
xenXMDomainConfigParse(virConnectPtr conn, virConfPtr conf) {
527
    virBuffer buf = VIR_BUFFER_INITIALIZER;
528
    const char *name;
529
    unsigned char uuid[VIR_UUID_BUFLEN];
530
    char uuidstr[VIR_UUID_STRING_BUFLEN];
531 532 533 534
    const char *str;
    int hvm = 0;
    long val;
    virConfValuePtr list;
535 536 537 538 539 540
    int vnc = 0, sdl = 0;
    char vfb[MAX_VFB];
    long vncdisplay;
    long vncunused = 1;
    const char *vnclisten = NULL;
    const char *vncpasswd = NULL;
541
    const char *keymap = NULL;
542
    xenUnifiedPrivatePtr priv = (xenUnifiedPrivatePtr) conn->privateData;
543 544
    virDomainDefPtr def = NULL;
    char *xml;
545 546

    if (xenXMConfigGetString(conf, "name", &name) < 0)
547
        return (NULL);
548
    if (xenXMConfigGetUUID(conf, "uuid", uuid) < 0)
549 550
        return (NULL);

551
    virBufferAddLit(&buf, "<domain type='xen'>\n");
552
    virBufferEscapeString(&buf, "  <name>%s</name>\n", name);
553
    virUUIDFormat(uuid, uuidstr);
554
    virBufferVSprintf(&buf, "  <uuid>%s</uuid>\n", uuidstr);
555

556
    if ((xenXMConfigGetString(conf, "builder", &str) == 0) &&
557
        STREQ(str, "hvm"))
558 559 560
        hvm = 1;

    if (hvm) {
561
        const char *boot;
562 563
        virBufferAddLit(&buf, "  <os>\n");
        virBufferAddLit(&buf, "    <type>hvm</type>\n");
564
        if (xenXMConfigGetString(conf, "kernel", &str) == 0)
565
            virBufferEscapeString(&buf, "    <loader>%s</loader>\n", str);
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583

        if (xenXMConfigGetString(conf, "boot", &boot) < 0)
            boot = "c";

        while (*boot) {
            const char *dev;
            switch (*boot) {
            case 'a':
                dev = "fd";
                break;
            case 'd':
                dev = "cdrom";
                break;
            case 'c':
            default:
                dev = "hd";
                break;
            }
584
            virBufferVSprintf(&buf, "    <boot dev='%s'/>\n", dev);
585 586 587
            boot++;
        }

588
        virBufferAddLit(&buf, "  </os>\n");
589 590
    } else {

591
        if (xenXMConfigGetString(conf, "bootloader", &str) == 0)
592
            virBufferEscapeString(&buf, "  <bootloader>%s</bootloader>\n", str);
593
        if (xenXMConfigGetString(conf, "bootargs", &str) == 0)
594
            virBufferEscapeString(&buf, "  <bootloader_args>%s</bootloader_args>\n", str);
595
        if (xenXMConfigGetString(conf, "kernel", &str) == 0) {
596 597
            virBufferAddLit(&buf, "  <os>\n");
            virBufferAddLit(&buf, "    <type>linux</type>\n");
598
            virBufferEscapeString(&buf, "    <kernel>%s</kernel>\n", str);
599
            if (xenXMConfigGetString(conf, "ramdisk", &str) == 0)
600
                virBufferEscapeString(&buf, "    <initrd>%s</initrd>\n", str);
601
            if (xenXMConfigGetString(conf, "extra", &str) == 0)
602 603
                virBufferEscapeString(&buf, "    <cmdline>%s</cmdline>\n", str);
            virBufferAddLit(&buf, "  </os>\n");
604 605 606
        }
    }

607
    if (xenXMConfigGetInt(conf, "memory", &val) < 0)
608
        val = MIN_XEN_GUEST_SIZE * 2;
609
    virBufferVSprintf(&buf, "  <currentMemory>%ld</currentMemory>\n",
610
                      val * 1024);
611 612 613

    if (xenXMConfigGetInt(conf, "maxmem", &val) < 0)
        if (xenXMConfigGetInt(conf, "memory", &val) < 0)
614
            val = MIN_XEN_GUEST_SIZE * 2;
615
    virBufferVSprintf(&buf, "  <memory>%ld</memory>\n", val * 1024);
616

617
    virBufferAddLit(&buf, "  <vcpu");
618 619
    if (xenXMConfigGetString(conf, "cpus", &str) == 0) {
        char *ranges;
620

621 622
        ranges = virConvertCpuSet(conn, str, 0);
        if (ranges != NULL) {
623
            virBufferVSprintf(&buf, " cpuset='%s'", ranges);
624
            VIR_FREE(ranges);
625
        } else
626
            virBufferVSprintf(&buf, " cpuset='%s'", str);
627
    }
628
    if (xenXMConfigGetInt(conf, "vcpus", &val) < 0)
629
        val = 1;
630
    virBufferVSprintf(&buf, ">%ld</vcpu>\n", val);
631

632
    if (xenXMConfigGetString(conf, "on_poweroff", &str) < 0)
633
        str = "destroy";
634
    virBufferVSprintf(&buf, "  <on_poweroff>%s</on_poweroff>\n", str);
635

636
    if (xenXMConfigGetString(conf, "on_reboot", &str) < 0)
637
        str = "restart";
638
    virBufferVSprintf(&buf, "  <on_reboot>%s</on_reboot>\n", str);
639

640
    if (xenXMConfigGetString(conf, "on_crash", &str) < 0)
641
        str = "restart";
642
    virBufferVSprintf(&buf, "  <on_crash>%s</on_crash>\n", str);
643 644 645


    if (hvm) {
646
        virBufferAddLit(&buf, "  <features>\n");
647
        if (xenXMConfigGetInt(conf, "pae", &val) == 0 &&
648
            val)
649
            virBufferAddLit(&buf, "    <pae/>\n");
650
        if (xenXMConfigGetInt(conf, "acpi", &val) == 0 &&
651
            val)
652
            virBufferAddLit(&buf, "    <acpi/>\n");
653
        if (xenXMConfigGetInt(conf, "apic", &val) == 0 &&
654
            val)
655 656
            virBufferAddLit(&buf, "    <apic/>\n");
        virBufferAddLit(&buf, "  </features>\n");
657 658 659

        if (xenXMConfigGetInt(conf, "localtime", &val) < 0)
            val = 0;
660
        virBufferVSprintf(&buf, "  <clock offset='%s'/>\n", val ? "localtime" : "utc");
661 662
    }

663
    virBufferAddLit(&buf, "  <devices>\n");
664

665
    if (hvm) {
666
        if (xenXMConfigGetString(conf, "device_model", &str) == 0)
667
            virBufferEscapeString(&buf, "    <emulator>%s</emulator>\n", str);
668 669
    }

670 671 672 673 674 675 676 677 678 679 680 681 682
    list = virConfGetValue(conf, "disk");
    if (list && list->type == VIR_CONF_LIST) {
        list = list->list;
        while (list) {
            int block = 0;
            int cdrom = 0;
            char src[PATH_MAX];
            char dev[NAME_MAX];
            char drvName[NAME_MAX] = "";
            char drvType[NAME_MAX] = "";
            char *head;
            char *offset;
            char *tmp, *tmp1;
683
            const char *bus;
684 685 686 687 688 689 690 691 692 693 694 695 696 697

            if ((list->type != VIR_CONF_STRING) || (list->str == NULL))
                goto skipdisk;
            head = list->str;

            /*
             * Disks have 3 components, SOURCE,DEST-DEVICE,MODE
             * eg, phy:/dev/HostVG/XenGuest1,xvda,w
             * The SOURCE is usually prefixed with a driver type,
             * and optionally driver sub-type
             * The DEST-DEVICE is optionally post-fixed with disk type
             */

            /* Extract the source */
698
            if (!(offset = strchr(head, ',')) || offset[0] == '\0')
699
                goto skipdisk;
700 701 702 703 704
            if ((offset - head) >= (PATH_MAX-1))
                goto skipdisk;
            strncpy(src, head, (offset - head));
            src[(offset-head)] = '\0';
            head = offset + 1;
705

706
            /* Extract the dest */
707
            if (!(offset = strchr(head, ',')) || offset[0] == '\0')
708 709 710 711 712 713
                goto skipdisk;
            if ((offset - head) >= (PATH_MAX-1))
                goto skipdisk;
            strncpy(dev, head, (offset - head));
            dev[(offset-head)] = '\0';
            head = offset + 1;
714 715


716
            /* Extract source driver type */
717 718
            if (!src[0]) {
                strcpy(drvName, "phy");
719
                tmp = &src[0];
720
            } else if ((tmp = strchr(src, ':')) != NULL) {
721 722 723
                strncpy(drvName, src, (tmp-src));
                drvName[tmp-src] = '\0';
            }
724 725

            /* And the source driver sub-type */
726
            if (STRPREFIX(drvName, "tap")) {
727
                if (!(tmp1 = strchr(tmp+1, ':')) || !tmp1[0])
728 729 730 731 732
                    goto skipdisk;
                strncpy(drvType, tmp+1, (tmp1-(tmp+1)));
                memmove(src, src+(tmp1-src)+1, strlen(src)-(tmp1-src));
            } else {
                drvType[0] = '\0';
733
                if (src[0] && tmp)
734
                        memmove(src, src+(tmp-src)+1, strlen(src)-(tmp-src));
735
            }
736

737
            /* phy: type indicates a block device */
738
            if (STREQ(drvName, "phy")) {
739 740
                block = 1;
            }
741

742
            /* Remove legacy ioemu: junk */
743
            if (STRPREFIX(dev, "ioemu:")) {
744 745 746 747
                memmove(dev, dev+6, strlen(dev)-5);
            }

            /* Check for a :cdrom/:disk postfix */
748
            if ((tmp = strchr(dev, ':')) != NULL) {
749
                if (STREQ(tmp, ":cdrom"))
750 751 752
                    cdrom = 1;
                tmp[0] = '\0';
            }
753

754 755 756 757 758 759 760 761
            if (STRPREFIX(dev, "xvd") || !hvm) {
                bus = "xen";
            } else if (STRPREFIX(dev, "sd")) {
                bus = "scsi";
            } else {
                bus = "ide";
            }

762
            virBufferVSprintf(&buf, "    <disk type='%s' device='%s'>\n",
763 764 765
                              block ? "block" : "file",
                              cdrom ? "cdrom" : "disk");
            if (drvType[0])
766
                virBufferVSprintf(&buf, "      <driver name='%s' type='%s'/>\n", drvName, drvType);
767
            else
768
                virBufferVSprintf(&buf, "      <driver name='%s'/>\n", drvName);
769 770
            if (src[0]) {
                virBufferVSprintf(&buf, "      <source %s=", block ? "dev" : "file");
A
Atsushi SAKAI 已提交
771 772
                virBufferEscapeString(&buf, "'%s'/>\n",  src);
            }
773 774
            virBufferEscapeString(&buf, "      <target dev='%s'", dev);
            virBufferVSprintf(&buf, " bus='%s'/>\n", bus);
775 776
            if (STREQ(head, "r") ||
                STREQ(head, "ro"))
777
                virBufferAddLit(&buf, "      <readonly/>\n");
778 779
            else if ((STREQ(head, "w!")) ||
                     (STREQ(head, "!")))
780 781
                virBufferAddLit(&buf, "      <shareable/>\n");
            virBufferAddLit(&buf, "    </disk>\n");
782 783 784 785

        skipdisk:
            list = list->next;
        }
786 787
    }

788
    if (hvm && priv->xendConfigVersion == 1) {
789
        if (xenXMConfigGetString(conf, "cdrom", &str) == 0) {
790 791
            virBufferAddLit(&buf, "    <disk type='file' device='cdrom'>\n");
            virBufferAddLit(&buf, "      <driver name='file'/>\n");
792
            virBufferEscapeString(&buf, "      <source file='%s'/>\n", str);
793
            virBufferAddLit(&buf, "      <target dev='hdc' bus='ide'/>\n");
794 795
            virBufferAddLit(&buf, "      <readonly/>\n");
            virBufferAddLit(&buf, "    </disk>\n");
796 797
        }
    }
798

799 800 801 802 803 804
    list = virConfGetValue(conf, "vif");
    if (list && list->type == VIR_CONF_LIST) {
        list = list->list;
        while (list) {
            int type = -1;
            char script[PATH_MAX];
805
            char model[10];
806 807
            char ip[16];
            char mac[18];
808
            char bridge[50];
809 810
            char *key;

811
            bridge[0] = '\0';
812 813 814
            mac[0] = '\0';
            script[0] = '\0';
            ip[0] = '\0';
815
            model[0] = '\0';
816 817 818

            if ((list->type != VIR_CONF_STRING) || (list->str == NULL))
                goto skipnic;
819

820 821 822
            key = list->str;
            while (key) {
                char *data;
823
                char *nextkey = strchr(key, ',');
824

825
                if (!(data = strchr(key, '=')) || (data[0] == '\0'))
826 827 828
                    goto skipnic;
                data++;

829
                if (STRPREFIX(key, "mac=")) {
830 831 832 833 834
                    int len = nextkey ? (nextkey - data) : 17;
                    if (len > 17)
                        len = 17;
                    strncpy(mac, data, len);
                    mac[len] = '\0';
835
                } else if (STRPREFIX(key, "bridge=")) {
836
                    int len = nextkey ? (nextkey - data) : sizeof(bridge)-1;
837
                    type = 1;
838 839 840 841
                    if (len > (sizeof(bridge)-1))
                        len = sizeof(bridge)-1;
                    strncpy(bridge, data, len);
                    bridge[len] = '\0';
842
                } else if (STRPREFIX(key, "script=")) {
843 844 845 846 847
                    int len = nextkey ? (nextkey - data) : PATH_MAX-1;
                    if (len > (PATH_MAX-1))
                        len = PATH_MAX-1;
                    strncpy(script, data, len);
                    script[len] = '\0';
848
                } else if (STRPREFIX(key, "model=")) {
849 850 851 852 853
                    int len = nextkey ? (nextkey - data) : sizeof(model)-1;
                    if (len > (sizeof(model)-1))
                        len = sizeof(model)-1;
                    strncpy(model, data, len);
                    model[len] = '\0';
854
                } else if (STRPREFIX(key, "ip=")) {
855 856 857 858 859 860
                    int len = nextkey ? (nextkey - data) : 15;
                    if (len > 15)
                        len = 15;
                    strncpy(ip, data, len);
                    ip[len] = '\0';
                }
861

862 863 864 865 866 867
                while (nextkey && (nextkey[0] == ',' ||
                                   nextkey[0] == ' ' ||
                                   nextkey[0] == '\t'))
                    nextkey++;
                key = nextkey;
            }
868

869 870
            /* XXX Forcing to pretend its a bridge */
            if (type == -1) {
871 872 873
                type = 1;
            }

874
            virBufferAddLit(&buf, "    <interface type='bridge'>\n");
875
            if (mac[0])
876
                virBufferVSprintf(&buf, "      <mac address='%s'/>\n", mac);
877
            if (type == 1 && bridge[0])
878
                virBufferVSprintf(&buf, "      <source bridge='%s'/>\n", bridge);
879
            if (script[0])
880
                virBufferEscapeString(&buf, "      <script path='%s'/>\n", script);
881
            if (ip[0])
882
                virBufferVSprintf(&buf, "      <ip address='%s'/>\n", ip);
883 884
            if (model[0])
                virBufferVSprintf(&buf, "      <model type='%s'/>\n", model);
885
            virBufferAddLit(&buf, "    </interface>\n");
886 887 888 889 890 891

        skipnic:
            list = list->next;
        }
    }

892 893
    if (hvm) {
        if (xenXMConfigGetString(conf, "usbdevice", &str) == 0 && str) {
894
            if (STREQ(str, "tablet"))
895
                virBufferAddLit(&buf, "    <input type='tablet' bus='usb'/>\n");
896
            else if (STREQ(str, "mouse"))
897
                virBufferAddLit(&buf, "    <input type='mouse' bus='usb'/>\n");
898 899 900 901 902
            /* Ignore else branch - probably some other non-input device we don't
               support in libvirt yet */
        }
    }

903
    /* HVM guests, or old PV guests use this config format */
904
    if (hvm || priv->xendConfigVersion < 3) {
905 906 907 908 909 910 911 912 913 914
        if (xenXMConfigGetInt(conf, "vnc", &val) == 0 && val) {
            vnc = 1;
            if (xenXMConfigGetInt(conf, "vncunused", &vncunused) < 0)
                vncunused = 1;
            if (xenXMConfigGetInt(conf, "vncdisplay", &vncdisplay) < 0)
                vncdisplay = 0;
            if (xenXMConfigGetString(conf, "vnclisten", &vnclisten) < 0)
                vnclisten = NULL;
            if (xenXMConfigGetString(conf, "vncpasswd", &vncpasswd) < 0)
                vncpasswd = NULL;
915 916
            if (xenXMConfigGetString(conf, "keymap", &keymap) < 0)
                keymap = NULL;
917
        }
918 919
        if (xenXMConfigGetInt(conf, "sdl", &val) == 0 && val)
            sdl = 1;
920 921
    }
    if (!hvm && !sdl && !vnc) { /* New PV guests use this format */
922 923 924 925 926 927 928 929 930 931 932
        list = virConfGetValue(conf, "vfb");
        if (list && list->type == VIR_CONF_LIST &&
            list->list && list->list->type == VIR_CONF_STRING &&
            list->list->str) {

            char *key = vfb;
            strncpy(vfb, list->list->str, MAX_VFB-1);
            vfb[MAX_VFB-1] = '\0';

            while (key) {
                char *data;
933
                char *nextkey = strchr(key, ',');
934 935 936 937 938 939
                char *end = nextkey;
                if (nextkey) {
                    *end = '\0';
                    nextkey++;
                }

940
                if (!(data = strchr(key, '=')) || (data[0] == '\0'))
941 942 943
                    break;
                data++;

944
                if (STRPREFIX(key, "type=sdl")) {
945
                    sdl = 1;
946
                } else if (STRPREFIX(key, "type=vnc")) {
947
                    vnc = 1;
948
                } else if (STRPREFIX(key, "vncunused=")) {
949
                    vncunused = strtol(key+10, NULL, 10);
950
                } else if (STRPREFIX(key, "vnclisten=")) {
951
                    vnclisten = key + 10;
952
                } else if (STRPREFIX(key, "vncpasswd=")) {
953
                    vncpasswd = key + 10;
954
                } else if (STRPREFIX(key, "keymap=")) {
955
                    keymap = key + 7;
956
                } else if (STRPREFIX(key, "vncdisplay=")) {
957
                    vncdisplay = strtol(key+11, NULL, 10);
958
                }
959

960 961 962 963 964 965
                while (nextkey && (nextkey[0] == ',' ||
                                   nextkey[0] == ' ' ||
                                   nextkey[0] == '\t'))
                    nextkey++;
                key = nextkey;
            }
966
        }
967
    }
968

969
    if (vnc || sdl) {
970
        virBufferVSprintf(&buf, "    <input type='mouse' bus='%s'/>\n", hvm ? "ps2":"xen");
971
    }
972
    if (vnc) {
973
        virBufferVSprintf(&buf,
974
                          "    <graphics type='vnc' port='%ld'",
975 976
                          (vncunused ? -1 : 5900+vncdisplay));
        if (vnclisten) {
977
            virBufferVSprintf(&buf, " listen='%s'", vnclisten);
978
        }
979
        if (vncpasswd) {
980
            virBufferEscapeString(&buf, " passwd='%s'", vncpasswd);
981
        }
982
        if (keymap) {
983
            virBufferEscapeString(&buf, " keymap='%s'", keymap);
984
        }
985
        virBufferAddLit(&buf, "/>\n");
986
    }
987
    if (sdl) {
988
        virBufferAddLit(&buf, "    <graphics type='sdl'/>\n");
989 990
    }

991
    if (hvm) {
992 993
        if (xenXMConfigGetString(conf, "parallel", &str) == 0) {
            if (STRNEQ(str, "none"))
994
                xend_parse_sexp_desc_char(conn, &buf, "parallel", 0, str, NULL);
995
        }
996 997
        if (xenXMConfigGetString(conf, "serial", &str) == 0) {
            if (STRNEQ(str, "none")) {
998
                xend_parse_sexp_desc_char(conn, &buf, "serial", 0, str, NULL);
999
                /* Add back-compat console tag for primary console */
1000
                xend_parse_sexp_desc_char(conn, &buf, "console", 0, str, NULL);
1001 1002 1003 1004
            }
        }
    } else {
        /* Paravirt implicitly always has a single console */
1005 1006 1007
        virBufferAddLit(&buf, "    <console type='pty'>\n");
        virBufferAddLit(&buf, "      <target port='0'/>\n");
        virBufferAddLit(&buf, "    </console>\n");
1008 1009
    }

D
Daniel Veillard 已提交
1010 1011 1012 1013 1014
    if (hvm) {
        if ((xenXMConfigGetString(conf, "soundhw", &str) == 0) && str) {
            char *soundxml;
            if ((soundxml = sound_string_to_xml(str))) {
                virBufferVSprintf(&buf, "%s", soundxml);
1015
                VIR_FREE(soundxml);
D
Daniel Veillard 已提交
1016 1017 1018 1019 1020 1021 1022 1023
            } else {
                xenXMError(conn, VIR_ERR_INTERNAL_ERROR,
                           _("parsing soundhw string failed."));
                goto error;
            }
        }
    }

1024 1025 1026
    virBufferAddLit(&buf, "  </devices>\n");

    virBufferAddLit(&buf, "</domain>\n");
1027

1028 1029
    if (virBufferError(&buf)) {
        xenXMError(conn, VIR_ERR_NO_MEMORY, _("allocate buffer"));
D
Daniel Veillard 已提交
1030
        goto error;
1031
    }
1032

1033 1034 1035 1036 1037 1038 1039 1040 1041
    xml = virBufferContentAndReset(&buf);

    if (!(def = virDomainDefParseString(conn, priv->caps, xml))) {
        VIR_FREE(xml);
        return NULL;
    }

    VIR_FREE(xml);
    return def;
D
Daniel Veillard 已提交
1042 1043

  error:
1044 1045
    str = virBufferContentAndReset(&buf);
    VIR_FREE(str);
D
Daniel Veillard 已提交
1046
    return NULL;
1047 1048 1049
}


1050 1051 1052 1053
/*
 * Turn a config record into a lump of XML describing the
 * domain, suitable for later feeding for virDomainCreateLinux
 */
1054
char *xenXMDomainDumpXML(virDomainPtr domain, int flags) {
1055 1056 1057 1058 1059 1060 1061 1062
    const char *filename;
    xenXMConfCachePtr entry;

    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
        xenXMError((domain ? domain->conn : NULL), VIR_ERR_INVALID_ARG,
                   __FUNCTION__);
        return(NULL);
    }
1063
    if (domain->id != -1)
1064 1065 1066 1067 1068 1069 1070 1071
        return (NULL);

    if (!(filename = virHashLookup(nameConfigMap, domain->name)))
        return (NULL);

    if (!(entry = virHashLookup(configCache, filename)))
        return (NULL);

1072
    return virDomainDefFormat(domain->conn, entry->def, flags);
1073 1074 1075
}


1076 1077 1078 1079
/*
 * Update amount of memory in the config file
 */
int xenXMDomainSetMemory(virDomainPtr domain, unsigned long memory) {
1080
    const char *filename;
1081 1082 1083 1084 1085 1086 1087 1088 1089
    xenXMConfCachePtr entry;

    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
        xenXMError((domain ? domain->conn : NULL), VIR_ERR_INVALID_ARG,
                   __FUNCTION__);
        return (-1);
    }
    if (domain->conn->flags & VIR_CONNECT_RO)
        return (-1);
1090
    if (domain->id != -1)
1091 1092
        return (-1);

1093 1094 1095 1096
    if (!(filename = virHashLookup(nameConfigMap, domain->name)))
        return (-1);

    if (!(entry = virHashLookup(configCache, filename)))
1097 1098
        return (-1);

1099 1100 1101
    entry->def->memory = memory;
    if (entry->def->memory > entry->def->maxmem)
        entry->def->memory = entry->def->maxmem;
1102 1103 1104 1105

    /* If this fails, should we try to undo our changes to the
     * in-memory representation of the config file. I say not!
     */
1106
    if (xenXMConfigSaveFile(domain->conn, entry->filename, entry->def) < 0)
1107 1108 1109 1110 1111 1112 1113 1114 1115
        return (-1);

    return (0);
}

/*
 * Update maximum memory limit in config
 */
int xenXMDomainSetMaxMemory(virDomainPtr domain, unsigned long memory) {
1116
    const char *filename;
1117 1118 1119 1120 1121 1122 1123 1124 1125
    xenXMConfCachePtr entry;

    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
        xenXMError((domain ? domain->conn : NULL), VIR_ERR_INVALID_ARG,
                   __FUNCTION__);
        return (-1);
    }
    if (domain->conn->flags & VIR_CONNECT_RO)
        return (-1);
1126
    if (domain->id != -1)
1127 1128
        return (-1);

1129 1130 1131 1132
    if (!(filename = virHashLookup(nameConfigMap, domain->name)))
        return (-1);

    if (!(entry = virHashLookup(configCache, filename)))
1133 1134
        return (-1);

1135 1136 1137
    entry->def->maxmem = memory;
    if (entry->def->memory > entry->def->maxmem)
        entry->def->memory = entry->def->maxmem;
1138 1139 1140 1141

    /* If this fails, should we try to undo our changes to the
     * in-memory representation of the config file. I say not!
     */
1142
    if (xenXMConfigSaveFile(domain->conn, entry->filename, entry->def) < 0)
1143 1144 1145 1146 1147 1148 1149 1150 1151
        return (-1);

    return (0);
}

/*
 * Get max memory limit from config
 */
unsigned long xenXMDomainGetMaxMemory(virDomainPtr domain) {
1152
    const char *filename;
1153 1154 1155 1156 1157 1158 1159
    xenXMConfCachePtr entry;

    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
        xenXMError((domain ? domain->conn : NULL), VIR_ERR_INVALID_ARG,
                   __FUNCTION__);
        return (-1);
    }
1160
    if (domain->id != -1)
1161 1162
        return (-1);

1163 1164 1165 1166
    if (!(filename = virHashLookup(nameConfigMap, domain->name)))
        return (-1);

    if (!(entry = virHashLookup(configCache, filename)))
1167 1168
        return (-1);

1169
    return entry->def->maxmem;
1170 1171 1172 1173 1174 1175
}

/*
 * Set the VCPU count in config
 */
int xenXMDomainSetVcpus(virDomainPtr domain, unsigned int vcpus) {
1176
    const char *filename;
1177 1178 1179 1180 1181 1182 1183 1184 1185
    xenXMConfCachePtr entry;

    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
        xenXMError((domain ? domain->conn : NULL), VIR_ERR_INVALID_ARG,
                   __FUNCTION__);
        return (-1);
    }
    if (domain->conn->flags & VIR_CONNECT_RO)
        return (-1);
1186
    if (domain->id != -1)
1187 1188
        return (-1);

1189 1190 1191 1192
    if (!(filename = virHashLookup(nameConfigMap, domain->name)))
        return (-1);

    if (!(entry = virHashLookup(configCache, filename)))
1193 1194
        return (-1);

1195
    entry->def->vcpus = vcpus;
1196 1197 1198 1199

    /* If this fails, should we try to undo our changes to the
     * in-memory representation of the config file. I say not!
     */
1200
    if (xenXMConfigSaveFile(domain->conn, entry->filename, entry->def) < 0)
1201 1202 1203 1204 1205
        return (-1);

    return (0);
}

1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
/**
 * xenXMDomainPinVcpu:
 * @domain: pointer to domain object
 * @vcpu: virtual CPU number (reserved)
 * @cpumap: pointer to a bit map of real CPUs (in 8-bit bytes)
 * @maplen: length of cpumap in bytes
 *
 * Set the vcpu affinity in config
 *
 * Returns 0 for success; -1 (with errno) on error
 */
int xenXMDomainPinVcpu(virDomainPtr domain,
                       unsigned int vcpu ATTRIBUTE_UNUSED,
                       unsigned char *cpumap, int maplen)
{
    const char *filename;
    xenXMConfCachePtr entry;
1223
    virBuffer mapbuf = VIR_BUFFER_INITIALIZER;
1224 1225 1226
    char *mapstr = NULL;
    int i, j, n, comma = 0;
    int ret = -1;
1227 1228
    char *cpuset = NULL;
    int maxcpu = XEN_MAX_PHYSICAL_CPU;
1229 1230 1231 1232 1233 1234 1235 1236

    if (domain == NULL || domain->conn == NULL || domain->name == NULL
        || cpumap == NULL || maplen < 1 || maplen > (int)sizeof(cpumap_t)) {
        xenXMError(domain ? domain->conn : NULL, VIR_ERR_INVALID_ARG,
                   __FUNCTION__);
        return -1;
    }
    if (domain->conn->flags & VIR_CONNECT_RO) {
1237 1238
        xenXMError (domain->conn, VIR_ERR_INVALID_ARG,
                    _("read only connection"));
1239 1240 1241
        return -1;
    }
    if (domain->id != -1) {
1242 1243
        xenXMError (domain->conn, VIR_ERR_INVALID_ARG,
                    _("not inactive domain"));
1244 1245 1246 1247
        return -1;
    }

    if (!(filename = virHashLookup(nameConfigMap, domain->name))) {
1248
        xenXMError (domain->conn, VIR_ERR_INTERNAL_ERROR, _("virHashLookup"));
1249 1250 1251 1252
        return -1;
    }
    if (!(entry = virHashLookup(configCache, filename))) {
        xenXMError (domain->conn, VIR_ERR_INTERNAL_ERROR,
1253
                    _("can't retrieve config file for domain"));
1254 1255 1256 1257 1258 1259 1260 1261 1262
        return -1;
    }

    /* 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))) {
                n = i*8 + j;

1263 1264
                if (comma)
                    virBufferAddLit (&mapbuf, ",");
1265 1266
                comma = 1;

1267
                virBufferVSprintf (&mapbuf, "%d", n);
1268 1269
            }

1270 1271 1272 1273 1274 1275
    if (virBufferError(&mapbuf)) {
        xenXMError(domain->conn, VIR_ERR_NO_MEMORY, _("allocate buffer"));
        return -1;
    }

    mapstr = virBufferContentAndReset(&mapbuf);
1276

1277 1278 1279 1280 1281 1282 1283 1284
    if (VIR_ALLOC_N(cpuset, maxcpu) < 0) {
        xenXMError(domain->conn, VIR_ERR_NO_MEMORY, _("allocate buffer"));
        goto cleanup;
    }
    if (virDomainCpuSetParse(domain->conn,
                             (const char **)&mapstr, 0,
                             cpuset, maxcpu) < 0)
        goto cleanup;
1285

1286 1287 1288 1289
    VIR_FREE(entry->def->cpumask);
    entry->def->cpumask = cpuset;
    entry->def->cpumasklen = maxcpu;
    cpuset = NULL;
1290

1291
    if (xenXMConfigSaveFile(domain->conn, entry->filename, entry->def) < 0)
1292 1293 1294 1295 1296
        goto cleanup;

    ret = 0;

 cleanup:
1297
    VIR_FREE(mapstr);
1298
    VIR_FREE(cpuset);
1299 1300 1301
    return (ret);
}

1302 1303 1304 1305
/*
 * Find an inactive domain based on its name
 */
virDomainPtr xenXMDomainLookupByName(virConnectPtr conn, const char *domname) {
1306
    const char *filename;
1307 1308
    xenXMConfCachePtr entry;
    virDomainPtr ret;
1309

1310 1311 1312 1313 1314 1315 1316 1317 1318
    if (!VIR_IS_CONNECT(conn)) {
        xenXMError(conn, VIR_ERR_INVALID_CONN, __FUNCTION__);
        return (NULL);
    }
    if (domname == NULL) {
        xenXMError(conn, VIR_ERR_INVALID_ARG, __FUNCTION__);
        return (NULL);
    }

1319
    if (xenXMConfigCacheRefresh (conn) < 0)
1320 1321
        return (NULL);

1322 1323 1324 1325
    if (!(filename = virHashLookup(nameConfigMap, domname)))
        return (NULL);

    if (!(entry = virHashLookup(configCache, filename))) {
1326 1327 1328
        return (NULL);
    }

1329
    if (!(ret = virGetDomain(conn, domname, entry->def->uuid))) {
1330 1331
        return (NULL);
    }
1332 1333 1334

    /* Ensure its marked inactive, because may be cached
       handle to a previously active domain */
1335
    ret->id = -1;
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347

    return (ret);
}


/*
 * Hash table iterator to search for a domain based on UUID
 */
static int xenXMDomainSearchForUUID(const void *payload, const char *name ATTRIBUTE_UNUSED, const void *data) {
    const unsigned char *wantuuid = (const unsigned char *)data;
    const xenXMConfCachePtr entry = (const xenXMConfCachePtr)payload;

1348
    if (!memcmp(entry->def->uuid, wantuuid, VIR_UUID_BUFLEN))
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
        return (1);

    return (0);
}

/*
 * Find an inactive domain based on its UUID
 */
virDomainPtr xenXMDomainLookupByUUID(virConnectPtr conn,
                                     const unsigned char *uuid) {
    xenXMConfCachePtr entry;
    virDomainPtr ret;

    if (!VIR_IS_CONNECT(conn)) {
        xenXMError(conn, VIR_ERR_INVALID_CONN, __FUNCTION__);
        return (NULL);
    }
    if (uuid == NULL) {
        xenXMError(conn, VIR_ERR_INVALID_ARG, __FUNCTION__);
        return (NULL);
    }

1371
    if (xenXMConfigCacheRefresh (conn) < 0)
1372 1373 1374 1375 1376 1377
        return (NULL);

    if (!(entry = virHashSearch(configCache, xenXMDomainSearchForUUID, (const void *)uuid))) {
        return (NULL);
    }

1378
    if (!(ret = virGetDomain(conn, entry->def->name, uuid))) {
1379 1380 1381
        return (NULL);
    }

1382 1383
    /* Ensure its marked inactive, because may be cached
       handle to a previously active domain */
1384
    ret->id = -1;
1385

1386 1387 1388 1389 1390 1391 1392 1393 1394
    return (ret);
}


/*
 * Start a domain from an existing defined config file
 */
int xenXMDomainCreate(virDomainPtr domain) {
    char *sexpr;
1395
    int ret;
1396
    xenUnifiedPrivatePtr priv;
1397 1398 1399 1400
    const char *filename;
    xenXMConfCachePtr entry;

    priv = (xenUnifiedPrivatePtr) domain->conn->privateData;
1401

1402
    if (domain->id != -1)
1403 1404
        return (-1);

1405
    if (!(filename = virHashLookup(nameConfigMap, domain->name)))
1406 1407
        return (-1);

1408
    if (!(entry = virHashLookup(configCache, filename)))
1409 1410
        return (-1);

1411
    if (!(sexpr = xenDaemonFormatSxpr(domain->conn, entry->def, priv->xendConfigVersion))) {
1412 1413 1414 1415 1416
        xenXMError(domain->conn, VIR_ERR_XML_ERROR,
                   _("failed to build sexpr"));
        return (-1);
    }

1417
    ret = xenDaemonDomainCreateLinux(domain->conn, sexpr);
1418
    VIR_FREE(sexpr);
1419 1420 1421 1422
    if (ret != 0) {
        return (-1);
    }

1423 1424
    if ((ret = xenDaemonDomainLookupByName_ids(domain->conn, domain->name,
                                               entry->def->uuid)) < 0) {
1425 1426
        return (-1);
    }
1427
    domain->id = ret;
1428

1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
    if ((ret = xend_wait_for_devices(domain->conn, domain->name)) < 0)
        goto cleanup;

    if ((ret = xenDaemonDomainResume(domain)) < 0)
        goto cleanup;

    return (0);

 cleanup:
    if (domain->id != -1) {
1439
        xenDaemonDomainDestroy(domain);
1440
        domain->id = -1;
1441
    }
1442
    return (-1);
1443 1444
}

1445 1446 1447 1448 1449

static
int xenXMConfigSetInt(virConfPtr conf, const char *setting, long l) {
    virConfValuePtr value = NULL;

1450
    if (VIR_ALLOC(value) < 0)
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
        return -1;

    value->type = VIR_CONF_LONG;
    value->next = NULL;
    value->l = l;

    return virConfSetValue(conf, setting, value);
}


static
int xenXMConfigSetString(virConfPtr conf, const char *setting, const char *str) {
    virConfValuePtr value = NULL;

1465
    if (VIR_ALLOC(value) < 0)
1466 1467 1468 1469 1470
        return -1;

    value->type = VIR_CONF_STRING;
    value->next = NULL;
    if (!(value->str = strdup(str))) {
1471
        VIR_FREE(value);
1472 1473 1474 1475 1476 1477 1478
        return -1;
    }

    return virConfSetValue(conf, setting, value);
}


1479 1480 1481 1482 1483
/*
 * Convenience method to set an int config param
 * based on an XPath expression
 */
static
1484 1485
int xenXMConfigSetIntFromXPath(virConnectPtr conn,
                               virConfPtr conf, xmlXPathContextPtr ctxt,
1486
                               const char *setting, const char *xpath,
1487
                               long scale, int allowMissing, const char *error) {
1488 1489 1490 1491 1492 1493 1494
    xmlXPathObjectPtr obj;
    long intval;
    char *strend;
    int ret = -1;

    obj = xmlXPathEval(BAD_CAST xpath, ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
1495 1496 1497 1498 1499
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
        if (allowMissing)
            ret = 0;
        else
            xenXMError(conn, VIR_ERR_XML_ERROR, error);
1500
        goto error;
1501
    }
1502 1503

    intval = strtol((char *)obj->stringval, &strend, 10);
1504 1505
    if (strend == (char *)obj->stringval) {
        xenXMError(conn, VIR_ERR_XML_ERROR, error);
1506
        goto error;
1507
    }
1508 1509

    if (scale > 0)
1510
        intval = intval * scale;
1511
    else if (scale < 0)
1512
        intval = intval / (-1*scale);
1513

1514
    if (xenXMConfigSetInt(conf, setting, intval) < 0)
1515 1516 1517 1518 1519
        goto error;

    ret = 0;

 error:
1520
    xmlXPathFreeObject(obj);
1521

1522
    return ret;
1523 1524 1525 1526 1527 1528 1529
}

/*
 * Convenience method to set a string param
 * based on an XPath expression
 */
static
1530 1531
int xenXMConfigSetStringFromXPath(virConnectPtr conn,
                                  virConfPtr conf, xmlXPathContextPtr ctxt,
1532
                                  const char *setting, const char *xpath,
1533
                                  int allowMissing, const char *error) {
1534 1535 1536 1537 1538 1539
    xmlXPathObjectPtr obj;
    int ret = -1;

    obj = xmlXPathEval(BAD_CAST xpath, ctxt);

    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
1540 1541 1542 1543 1544
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
        if (allowMissing)
            ret = 0;
        else
            xenXMError(conn, VIR_ERR_XML_ERROR, error);
1545
        goto error;
1546
    }
1547

1548
    if (xenXMConfigSetString(conf, setting, (const char *)obj->stringval) < 0)
1549 1550 1551 1552 1553
        goto error;

    ret = 0;

 error:
1554
    xmlXPathFreeObject(obj);
1555

1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
    return ret;
}

static int xenXMParseXMLDisk(xmlNodePtr node, int hvm, int xendConfigVersion, char **disk) {
    xmlNodePtr cur;
    xmlChar *type = NULL;
    xmlChar *device = NULL;
    xmlChar *source = NULL;
    xmlChar *target = NULL;
    xmlChar *drvName = NULL;
    xmlChar *drvType = NULL;
    int readonly = 0;
    int shareable = 0;
    int typ = 0;
    int cdrom = 0;
    int ret = -1;
    int buflen = 0;
    char *buf = NULL;

    type = xmlGetProp(node, BAD_CAST "type");
    if (type != NULL) {
        if (xmlStrEqual(type, BAD_CAST "file"))
            typ = 0;
        else if (xmlStrEqual(type, BAD_CAST "block"))
            typ = 1;
        xmlFree(type);
    }
    device = xmlGetProp(node, BAD_CAST "device");

    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
            if ((source == NULL) &&
                (xmlStrEqual(cur->name, BAD_CAST "source"))) {

                if (typ == 0)
                    source = xmlGetProp(cur, BAD_CAST "file");
                else
                    source = xmlGetProp(cur, BAD_CAST "dev");
            } else if ((target == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "target"))) {
                target = xmlGetProp(cur, BAD_CAST "dev");
            } else if ((drvName == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "driver"))) {
                drvName = xmlGetProp(cur, BAD_CAST "name");
1601
                if (drvName && STREQ((const char *)drvName, "tap"))
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
                    drvType = xmlGetProp(cur, BAD_CAST "type");
            } else if (xmlStrEqual(cur->name, BAD_CAST "readonly")) {
                readonly = 1;
            } else if (xmlStrEqual(cur->name, BAD_CAST "shareable")) {
                shareable = 1;
            }
        }
        cur = cur->next;
    }

    if (target == NULL) {
1613 1614
        xmlFree(source);
        xmlFree(device);
1615 1616 1617 1618 1619 1620 1621 1622
        return (-1);
    }

    /* Xend (all versions) put the floppy device config
     * under the hvm (image (os)) block
     */
    if (hvm &&
        device &&
1623
        STREQ((const char *)device, "floppy")) {
1624 1625 1626 1627 1628 1629 1630
        ret = 0;
        goto cleanup;
    }

    /* Xend <= 3.0.2 doesn't include cdrom config here */
    if (hvm &&
        device &&
1631
        STREQ((const char *)device, "cdrom")) {
1632 1633 1634 1635 1636 1637 1638 1639
        if (xendConfigVersion == 1) {
            ret = 0;
            goto cleanup;
        } else {
            cdrom = 1;
        }
    }

1640
    if (source == NULL && !cdrom) {
1641 1642
        xmlFree(target);
        xmlFree(device);
1643 1644 1645
        return (-1);
    }

1646 1647
    if (drvName) {
        buflen += strlen((const char*)drvName) + 1;
1648
        if (STREQ((const char*)drvName, "tap")) {
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
            if (drvType)
                buflen += strlen((const char*)drvType) + 1;
            else
                buflen += 4;
        }
    } else {
        if (typ == 0)
            buflen += 5;
        else
            buflen += 4;
    }

1661 1662 1663 1664
    if(source)
        buflen += strlen((const char*)source) + 1;
    else
        buflen += 1;
1665 1666 1667 1668 1669 1670 1671 1672 1673
    buflen += strlen((const char*)target) + 1;
    if (hvm && xendConfigVersion == 1) /* ioemu: */
        buflen += 6;

    if (cdrom) /* :cdrom */
        buflen += 6;

    buflen += 2; /* mode */

1674
    if (VIR_ALLOC_N(buf, buflen) < 0)
1675 1676
        goto cleanup;

1677 1678 1679
    if(source) {
        if (drvName) {
            strcpy(buf, (const char*)drvName);
1680
            if (STREQ((const char*)drvName, "tap")) {
1681 1682 1683 1684 1685 1686 1687 1688 1689
                strcat(buf, ":");
                if (drvType)
                    strcat(buf, (const char*)drvType);
                else
                    strcat(buf, "aio");
            }
        } else {
            if (typ == 0)
                strcpy(buf, "file");
1690
            else
1691
                strcpy(buf, "phy");
1692
        }
1693 1694
        strcat(buf, ":");
        strcat(buf, (const char*)source);
1695
    } else {
1696
        strcpy(buf, "");
1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
    }
    strcat(buf, ",");
    if (hvm && xendConfigVersion == 1)
        strcat(buf, "ioemu:");
    strcat(buf, (const char*)target);
    if (cdrom)
        strcat(buf, ":cdrom");

    if (readonly)
        strcat(buf, ",r");
    else if (shareable)
        strcat(buf, ",!");
    else
        strcat(buf, ",w");
    ret = 0;
 cleanup:
    xmlFree(drvType);
    xmlFree(drvName);
    xmlFree(device);
    xmlFree(target);
1717
    xmlFree(source);
1718 1719
    *disk = buf;

1720 1721
    return (ret);
}
1722
static char *xenXMParseXMLVif(virConnectPtr conn, xmlNodePtr node, int hvm) {
1723 1724 1725 1726 1727
    xmlNodePtr cur;
    xmlChar *type = NULL;
    xmlChar *source = NULL;
    xmlChar *mac = NULL;
    xmlChar *script = NULL;
1728
    xmlChar *model = NULL;
1729 1730 1731 1732
    xmlChar *ip = NULL;
    int typ = 0;
    char *buf = NULL;
    int buflen = 0;
1733
    char *bridge = NULL;
1734 1735 1736 1737 1738 1739 1740

    type = xmlGetProp(node, BAD_CAST "type");
    if (type != NULL) {
        if (xmlStrEqual(type, BAD_CAST "bridge"))
            typ = 0;
        else if (xmlStrEqual(type, BAD_CAST "ethernet"))
            typ = 1;
1741 1742
        else if (xmlStrEqual(type, BAD_CAST "network"))
            typ = 2;
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752
        xmlFree(type);
    }
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
            if ((source == NULL) &&
                (xmlStrEqual(cur->name, BAD_CAST "source"))) {

                if (typ == 0)
                    source = xmlGetProp(cur, BAD_CAST "bridge");
1753
                else if (typ == 1)
1754
                    source = xmlGetProp(cur, BAD_CAST "dev");
1755 1756
                else
                    source = xmlGetProp(cur, BAD_CAST "network");
1757 1758 1759
            } else if ((mac == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "mac"))) {
                mac = xmlGetProp(cur, BAD_CAST "address");
1760 1761 1762
            } else if ((model == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "model"))) {
                model = xmlGetProp(cur, BAD_CAST "type");
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
            } else if ((ip == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "ip"))) {
                ip = xmlGetProp(cur, BAD_CAST "address");
            } else if ((script == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "script"))) {
                script = xmlGetProp(cur, BAD_CAST "path");
            }
        }
        cur = cur->next;
    }
1773

1774 1775 1776 1777 1778 1779 1780
    if (!mac) {
        goto cleanup;
    }
    buflen += 5 + strlen((const char *)mac);
    if (source) {
        if (typ == 0) {
            buflen += 8 + strlen((const char *)source);
1781
        } else if (typ == 1) {
1782
            buflen += 5 + strlen((const char *)source);
1783 1784 1785 1786 1787 1788 1789 1790 1791
        } else {
            virNetworkPtr network = virNetworkLookupByName(conn, (const char *) source);
            if (!network || !(bridge = virNetworkGetBridgeName(network))) {
                if (network)
                    virNetworkFree(network);
                goto cleanup;
            }
            virNetworkFree(network);
            buflen += 8 + strlen(bridge);
1792 1793 1794 1795 1796 1797
        }
    }
    if (hvm)
        buflen += 11;
    if (script)
        buflen += 8 + strlen((const char*)script);
1798 1799
    if (model)
        buflen += 7 + strlen((const char*)model);
1800 1801 1802
    if (ip)
        buflen += 4 + strlen((const char*)ip);

1803
    if (VIR_ALLOC_N(buf, buflen) < 0)
1804 1805 1806 1807 1808 1809 1810 1811
        goto cleanup;

    strcpy(buf, "mac=");
    strcat(buf, (const char*)mac);
    if (source) {
        if (typ == 0) {
            strcat(buf, ",bridge=");
            strcat(buf, (const char*)source);
1812 1813
        } else if (typ == 1) {
            strcat(buf, ",dev=");
1814
            strcat(buf, (const char*)source);
1815 1816 1817
        } else {
            strcat(buf, ",bridge=");
            strcat(buf, bridge);
1818 1819 1820 1821 1822 1823 1824 1825 1826
        }
    }
    if (hvm) {
        strcat(buf, ",type=ioemu");
    }
    if (script) {
        strcat(buf, ",script=");
        strcat(buf, (const char*)script);
    }
1827 1828 1829 1830
    if (model) {
        strcat(buf, ",model=");
        strcat(buf, (const char*)model);
    }
1831 1832 1833 1834
    if (ip) {
        strcat(buf, ",ip=");
        strcat(buf, (const char*)ip);
    }
1835

1836
 cleanup:
1837
    VIR_FREE(bridge);
1838 1839 1840 1841
    xmlFree(mac);
    xmlFree(source);
    xmlFree(script);
    xmlFree(ip);
1842
    xmlFree(model);
1843 1844 1845 1846 1847

    return buf;
}


1848 1849
virConfPtr xenXMDomainConfigFormat(virConnectPtr conn,
                                   virDomainDefPtr def) {
1850 1851 1852 1853 1854 1855
    xmlDocPtr doc = NULL;
    xmlNodePtr node;
    xmlXPathObjectPtr obj = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlChar *prop = NULL;
    virConfPtr conf = NULL;
1856
    int hvm = 0, i;
1857
    xenUnifiedPrivatePtr priv;
1858
    char *cpus;
1859 1860 1861 1862 1863 1864
    char *xml;

    priv = (xenUnifiedPrivatePtr) conn->privateData;

    if (!(xml = virDomainDefFormat(conn, def, VIR_DOMAIN_XML_SECURE)))
        return NULL;
1865 1866 1867 1868

    doc = xmlReadDoc((const xmlChar *) xml, "domain.xml", NULL,
                     XML_PARSE_NOENT | XML_PARSE_NONET |
                     XML_PARSE_NOERROR | XML_PARSE_NOWARNING);
1869
    VIR_FREE(xml);
1870
    if (doc == NULL) {
1871 1872
        xenXMError(conn, VIR_ERR_XML_ERROR,
                   _("cannot read XML domain definition"));
1873 1874 1875
        return (NULL);
    }
    node = xmlDocGetRootElement(doc);
1876
    if ((node == NULL) || (!xmlStrEqual(node->name, BAD_CAST "domain"))) {
1877 1878
        xenXMError(conn, VIR_ERR_XML_ERROR,
                   _("missing top level domain element"));
1879
        goto error;
1880
    }
1881 1882 1883 1884

    prop = xmlGetProp(node, BAD_CAST "type");
    if (prop != NULL) {
        if (!xmlStrEqual(prop, BAD_CAST "xen")) {
1885 1886
            xenXMError(conn, VIR_ERR_XML_ERROR,
                       _("domain type is invalid"));
1887 1888 1889 1890 1891
            goto error;
        }
        xmlFree(prop);
        prop = NULL;
    }
1892
    if (!(ctxt = xmlXPathNewContext(doc))) {
1893 1894
        xenXMError(conn, VIR_ERR_INTERNAL_ERROR,
                   _("cannot create XPath context"));
1895
        goto error;
1896
    }
1897 1898 1899
    if (!(conf = virConfNew()))
        goto error;

1900 1901 1902

    if (xenXMConfigSetStringFromXPath(conn, conf, ctxt, "name", "string(/domain/name)", 0,
                                      "domain name element missing") < 0)
1903 1904
        goto error;

1905 1906
    if (xenXMConfigSetStringFromXPath(conn, conf, ctxt, "uuid", "string(/domain/uuid)", 0,
                                      "domain uuid element missing") < 0)
1907 1908
        goto error;

1909 1910
    if (xenXMConfigSetIntFromXPath(conn, conf, ctxt, "maxmem", "string(/domain/memory)", -1024, 0,
                                   "domain memory element missing") < 0)
1911 1912
        goto error;

1913 1914
    if (xenXMConfigSetIntFromXPath(conn, conf, ctxt, "memory", "string(/domain/memory)", -1024, 0,
                                   "domain memory element missing") < 0)
1915 1916
        goto error;

1917 1918
    if (xenXMConfigSetIntFromXPath(conn, conf, ctxt, "memory", "string(/domain/currentMemory)", -1024, 1,
                                   "domain currentMemory element missing") < 0)
1919 1920
        goto error;

1921
    if (xenXMConfigSetInt(conf, "vcpus", 1) < 0)
1922 1923
        goto error;

1924 1925
    if (xenXMConfigSetIntFromXPath(conn, conf, ctxt, "vcpus", "string(/domain/vcpu)", 0, 1,
                                   "cannot set vcpus config parameter") < 0)
1926 1927
        goto error;

1928 1929 1930 1931
    cpus = virXPathString("string(/domain/vcpu/@cpuset)", ctxt);
    if (cpus != NULL) {
        char *ranges;

1932
        ranges = virConvertCpuSet(conn, cpus, 0);
1933 1934 1935 1936 1937
        VIR_FREE(cpus);
        if (ranges == NULL) {
            goto error;
        }
        if (xenXMConfigSetString(conf, "cpus", ranges) < 0) {
1938
            VIR_FREE(ranges);
1939
            goto error;
1940
        }
1941
        VIR_FREE(ranges);
1942 1943
    }

1944 1945
    obj = xmlXPathEval(BAD_CAST "string(/domain/os/type)", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_STRING) &&
1946
        (obj->stringval != NULL) && STREQ((char*)obj->stringval, "hvm"))
1947 1948
        hvm = 1;
    xmlXPathFreeObject(obj);
1949
    obj = NULL;
1950 1951 1952

    if (hvm) {
        const char *boot = "c";
1953
        int clockLocal = 0;
1954 1955 1956 1957 1958 1959 1960
        if (xenXMConfigSetString(conf, "builder", "hvm") < 0)
            goto error;

        if (xenXMConfigSetStringFromXPath(conn, conf, ctxt, "kernel", "string(/domain/os/loader)", 1,
                                          "cannot set the os loader parameter") < 0)
            goto error;

D
Daniel P. Berrange 已提交
1961
        obj = xmlXPathEval(BAD_CAST "string(/domain/os/boot/@dev)", ctxt);
1962 1963
        if ((obj != NULL) && (obj->type == XPATH_STRING) &&
            (obj->stringval != NULL)) {
1964
            if (STREQ((const char*)obj->stringval, "fd"))
1965
                boot = "a";
1966
            else if (STREQ((const char*)obj->stringval, "hd"))
1967
                boot = "c";
1968
            else if (STREQ((const char*)obj->stringval, "cdrom"))
1969 1970 1971
                boot = "d";
        }
        xmlXPathFreeObject(obj);
1972
        obj = NULL;
1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987
        if (xenXMConfigSetString(conf, "boot", boot) < 0)
            goto error;

        if (xenXMConfigSetIntFromXPath(conn, conf, ctxt, "pae", "string(count(/domain/features/pae))", 0, 0,
                                       "cannot set the pae parameter") < 0)
            goto error;

        if (xenXMConfigSetIntFromXPath(conn, conf, ctxt, "acpi", "string(count(/domain/features/acpi))", 0, 0,
                                       "cannot set the acpi parameter") < 0)
            goto error;

        if (xenXMConfigSetIntFromXPath(conn, conf, ctxt, "apic", "string(count(/domain/features/apic))", 0, 0,
                                       "cannot set the apic parameter") < 0)
            goto error;

1988 1989 1990
        obj = xmlXPathEval(BAD_CAST "string(/domain/clock/@offset)", ctxt);
        if ((obj != NULL) && (obj->type == XPATH_STRING) &&
            (obj->stringval != NULL)) {
1991
            if (STREQ((const char*)obj->stringval, "localtime"))
1992 1993 1994
                clockLocal = 1;
        }
        xmlXPathFreeObject(obj);
1995
        obj = NULL;
1996 1997 1998
        if (xenXMConfigSetInt(conf, "localtime", clockLocal) < 0)
            goto error;

1999
        if (priv->xendConfigVersion == 1) {
2000 2001 2002 2003 2004 2005 2006 2007
            if (xenXMConfigSetStringFromXPath(conn, conf, ctxt, "cdrom", "string(/domain/devices/disk[@device='cdrom']/source/@file)", 1,
                                              "cannot set the cdrom parameter") < 0)
                goto error;
        }
    } else {
        if (xenXMConfigSetStringFromXPath(conn, conf, ctxt, "bootloader", "string(/domain/bootloader)", 1,
                                          "cannot set the bootloader parameter") < 0)
            goto error;
2008 2009 2010
        if (xenXMConfigSetStringFromXPath(conn, conf, ctxt, "bootargs", "string(/domain/bootloader_args)", 1,
                                          "cannot set the bootloader_args parameter") < 0)
            goto error;
2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
        if (xenXMConfigSetStringFromXPath(conn, conf, ctxt, "kernel", "string(/domain/os/kernel)", 1,
                                          "cannot set the kernel parameter") < 0)
            goto error;
        if (xenXMConfigSetStringFromXPath(conn, conf, ctxt, "ramdisk", "string(/domain/os/initrd)", 1,
                                          "cannot set the ramdisk parameter") < 0)
            goto error;
        if (xenXMConfigSetStringFromXPath(conn, conf, ctxt, "extra", "string(/domain/os/cmdline)", 1,
                                          "cannot set the cmdline parameter") < 0)
            goto error;

    }
2022

2023 2024
    if (xenXMConfigSetStringFromXPath(conn, conf, ctxt, "on_poweroff", "string(/domain/on_poweroff)", 1,
                                      "cannot set the on_poweroff parameter") < 0)
2025 2026
        goto error;

2027 2028
    if (xenXMConfigSetStringFromXPath(conn, conf, ctxt, "on_reboot", "string(/domain/on_reboot)", 1,
                                      "cannot set the on_reboot parameter") < 0)
2029 2030
        goto error;

2031 2032
    if (xenXMConfigSetStringFromXPath(conn, conf, ctxt, "on_crash", "string(/domain/on_crash)", 1,
                                      "cannot set the on_crash parameter") < 0)
2033 2034 2035
        goto error;


2036 2037 2038 2039 2040
    if (hvm) {
        if (xenXMConfigSetStringFromXPath(conn, conf, ctxt, "device_model", "string(/domain/devices/emulator)", 1,
                                          "cannot set the device_model parameter") < 0)
            goto error;

2041 2042 2043
        if (xenXMConfigSetStringFromXPath(conn, conf, ctxt, "usbdevice", "string(/domain/devices/input[@bus='usb' or (not(@bus) and @type='tablet')]/@type)", 1,
                                          "cannot set the usbdevice parameter") < 0)
            goto error;
2044 2045
    }

2046
    if (hvm || priv->xendConfigVersion < 3) {
2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
        if (xenXMConfigSetIntFromXPath(conn, conf, ctxt, "sdl", "string(count(/domain/devices/graphics[@type='sdl']))", 0, 0,
                                       "cannot set the sdl parameter") < 0)
            goto error;
        if (xenXMConfigSetIntFromXPath(conn, conf, ctxt, "vnc", "string(count(/domain/devices/graphics[@type='vnc']))", 0, 0,
                                       "cannot set the vnc parameter") < 0)
            goto error;
        if (xenXMConfigSetIntFromXPath(conn, conf, ctxt, "vncunused", "string(count(/domain/devices/graphics[@type='vnc' and @port='-1']))", 0, 0,
                                       "cannot set the vncunused parameter") < 0)
            goto error;
        if (xenXMConfigSetStringFromXPath(conn, conf, ctxt, "vnclisten", "string(/domain/devices/graphics[@type='vnc']/@listen)", 1,
                                          "cannot set the vnclisten parameter") < 0)
            goto error;
        if (xenXMConfigSetStringFromXPath(conn, conf, ctxt, "vncpasswd", "string(/domain/devices/graphics[@type='vnc']/@passwd)", 1,
                                          "cannot set the vncpasswd parameter") < 0)
            goto error;
2062 2063 2064
        if (xenXMConfigSetStringFromXPath(conn, conf, ctxt, "keymap", "string(/domain/devices/graphics[@type='vnc']/@keymap)", 1,
                                          "cannot set the keymap parameter") < 0)
            goto error;
2065

2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
        obj = xmlXPathEval(BAD_CAST "string(/domain/devices/graphics[@type='vnc']/@port)", ctxt);
        if ((obj != NULL) && (obj->type == XPATH_STRING) &&
            (obj->stringval != NULL)) {
            int port = strtol((const char *)obj->stringval, NULL, 10);
            if (port != -1) {
                char portstr[50];
                snprintf(portstr, sizeof(portstr), "%d", port-5900);
                if (xenXMConfigSetString(conf, "vncdisplay", portstr) < 0)
                    goto error;
            }
        }
        xmlXPathFreeObject(obj);
2078 2079 2080 2081 2082
    } else {
        virConfValuePtr vfb;
        obj = xmlXPathEval(BAD_CAST "/domain/devices/graphics", ctxt);
        if ((obj != NULL) && (obj->type == XPATH_NODESET) &&
            (obj->nodesetval != NULL) && (obj->nodesetval->nodeNr >= 0)) {
2083
            if (VIR_ALLOC(vfb) < 0) {
2084
                xenXMError(conn, VIR_ERR_NO_MEMORY, _("config"));
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
                goto error;
            }
            vfb->type = VIR_CONF_LIST;
            vfb->list = NULL;
            for (i = obj->nodesetval->nodeNr -1 ; i >= 0 ; i--) {
                xmlChar *type;
                char *val = NULL;

                if (!(type = xmlGetProp(obj->nodesetval->nodeTab[i], BAD_CAST "type"))) {
                    continue;
                }
2096
                if (STREQ((const char*)type, "sdl")) {
2097
                    val = strdup("type=sdl");
2098
                } else if (STREQ((const char*)type, "vnc")) {
2099 2100 2101 2102
                    int len = 8 + 1; /* type=vnc & NULL */
                    xmlChar *vncport = xmlGetProp(obj->nodesetval->nodeTab[i], BAD_CAST "port");
                    xmlChar *vnclisten = xmlGetProp(obj->nodesetval->nodeTab[i], BAD_CAST "listen");
                    xmlChar *vncpasswd = xmlGetProp(obj->nodesetval->nodeTab[i], BAD_CAST "passwd");
2103
                    xmlChar *keymap = xmlGetProp(obj->nodesetval->nodeTab[i], BAD_CAST "keymap");
2104
                    int vncunused = vncport ? (STREQ((const char*)vncport, "-1") ? 1 : 0) : 1;
2105 2106 2107 2108 2109 2110 2111 2112
                    if (vncunused)
                        len += 12;
                    else
                        len += 12 + strlen((const char*)vncport);/* vncdisplay= */
                    if (vnclisten)
                        len += 11 + strlen((const char*)vnclisten);
                    if (vncpasswd)
                        len += 11 + strlen((const char*)vncpasswd);
2113 2114
                    if (keymap)
                        len += 8 + strlen((const char*)keymap);
2115 2116
                    if (VIR_ALLOC_N(val, len) < 0) {
                        xmlFree(type);
2117
                        xmlFree(vncport);
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149
                        xmlFree(vnclisten);
                        xmlFree(vncpasswd);
                        xmlFree(keymap);
                        VIR_FREE(vfb);
                        xenXMError (conn, VIR_ERR_NO_MEMORY, strerror (errno));
                        goto error;
                    }
                    strcpy(val, "type=vnc");
                    if (vncunused) {
                        strcat(val, ",vncunused=1");
                    } else {
                        char portstr[50];
                        int port = atoi((const char*)vncport);
                        snprintf(portstr, sizeof(portstr), "%d", port-5900);
                        strcat(val, ",vncdisplay=");
                        strcat(val, portstr);
                    }
                    xmlFree(vncport);
                    if (vnclisten) {
                        strcat(val, ",vnclisten=");
                        strcat(val, (const char*)vnclisten);
                        xmlFree(vnclisten);
                    }
                    if (vncpasswd) {
                        strcat(val, ",vncpasswd=");
                        strcat(val, (const char*)vncpasswd);
                        xmlFree(vncpasswd);
                    }
                    if (keymap) {
                        strcat(val, ",keymap=");
                        strcat(val, (const char*)keymap);
                        xmlFree(keymap);
2150 2151 2152 2153 2154
                    }
                }
                xmlFree(type);
                if (val) {
                    virConfValuePtr disp;
2155 2156 2157
                    if (VIR_ALLOC(disp) < 0) {
                        VIR_FREE(val);
                        VIR_FREE(vfb);
2158
                        xenXMError(conn, VIR_ERR_NO_MEMORY, _("config"));
2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177
                        goto error;
                    }
                    disp->type = VIR_CONF_STRING;
                    disp->str = val;
                    disp->next = vfb->list;
                    vfb->list = disp;
                }
            }
            if (virConfSetValue(conf, "vfb", vfb) < 0)
                goto error;
        }
        xmlXPathFreeObject(obj);
    }

    /* analyze of the devices */
    obj = xmlXPathEval(BAD_CAST "/domain/devices/disk", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_NODESET) &&
        (obj->nodesetval != NULL) && (obj->nodesetval->nodeNr >= 0)) {
        virConfValuePtr disks;
2178
        if (VIR_ALLOC(disks) < 0) {
2179
            xenXMError(conn, VIR_ERR_NO_MEMORY, _("config"));
2180 2181 2182 2183 2184 2185 2186
            goto error;
        }
        disks->type = VIR_CONF_LIST;
        disks->list = NULL;
        for (i = obj->nodesetval->nodeNr -1 ; i >= 0 ; i--) {
            virConfValuePtr thisDisk;
            char *disk = NULL;
2187 2188
            if (xenXMParseXMLDisk(obj->nodesetval->nodeTab[i], hvm, priv->xendConfigVersion, &disk) < 0) {
                virConfFreeValue(disks);
2189
                goto error;
2190
            }
2191
            if (disk) {
2192 2193 2194
                if (VIR_ALLOC(thisDisk) < 0) {
                    VIR_FREE(disk);
                    virConfFreeValue(disks);
2195
                    xenXMError(conn, VIR_ERR_NO_MEMORY, _("config"));
2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
                    goto error;
                }
                thisDisk->type = VIR_CONF_STRING;
                thisDisk->str = disk;
                thisDisk->next = disks->list;
                disks->list = thisDisk;
            }
        }
        if (virConfSetValue(conf, "disk", disks) < 0)
            goto error;
    }
    xmlXPathFreeObject(obj);

    obj = xmlXPathEval(BAD_CAST "/domain/devices/interface", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_NODESET) &&
        (obj->nodesetval != NULL) && (obj->nodesetval->nodeNr >= 0)) {
        virConfValuePtr vifs;
2213
        if (VIR_ALLOC(vifs) < 0) {
2214
            xenXMError(conn, VIR_ERR_NO_MEMORY, _("config"));
2215 2216 2217 2218
            goto error;
        }
        vifs->type = VIR_CONF_LIST;
        vifs->list = NULL;
D
Daniel Veillard 已提交
2219
        for (i = obj->nodesetval->nodeNr - 1; i >= 0; i--) {
2220
            virConfValuePtr thisVif;
2221
            char *vif = xenXMParseXMLVif(conn, obj->nodesetval->nodeTab[i], hvm);
2222 2223
            if (!vif) {
                virConfFreeValue(vifs);
2224
                goto error;
2225 2226 2227 2228
            }
            if (VIR_ALLOC(thisVif) < 0) {
                VIR_FREE(vif);
                virConfFreeValue(vifs);
2229
                xenXMError(conn, VIR_ERR_NO_MEMORY, _("config"));
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243
                goto error;
            }
            thisVif->type = VIR_CONF_STRING;
            thisVif->str = vif;
            thisVif->next = vifs->list;
            vifs->list = thisVif;
        }
        if (virConfSetValue(conf, "vif", vifs) < 0)
            goto error;
    }
    xmlXPathFreeObject(obj);
    obj = NULL;

    if (hvm) {
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256
        xmlNodePtr cur;
        cur = virXPathNode("/domain/devices/parallel[1]", ctxt);
        if (cur != NULL) {
            char scratch[PATH_MAX];

            if (virDomainParseXMLOSDescHVMChar(conn, scratch, sizeof(scratch), cur) < 0) {
                goto error;
            }

            if (xenXMConfigSetString(conf, "parallel", scratch) < 0)
                goto error;
        } else {
            if (xenXMConfigSetString(conf, "parallel", "none") < 0)
2257 2258
                goto error;
        }
2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275

        cur = virXPathNode("/domain/devices/serial[1]", ctxt);
        if (cur != NULL) {
            char scratch[PATH_MAX];
            if (virDomainParseXMLOSDescHVMChar(conn, scratch, sizeof(scratch), cur) < 0)
                goto error;
            if (xenXMConfigSetString(conf, "serial", scratch) < 0)
                goto error;
        } else {
            if (virXPathBoolean("count(/domain/devices/console) > 0", ctxt)) {
                if (xenXMConfigSetString(conf, "serial", "pty") < 0)
                    goto error;
            } else {
                if (xenXMConfigSetString(conf, "serial", "none") < 0)
                    goto error;
            }
        }
D
Daniel Veillard 已提交
2276 2277 2278 2279 2280 2281

        if (virXPathNode("/domain/devices/sound", ctxt)) {
            char *soundstr;
            if (!(soundstr = virBuildSoundStringFromXML(conn, ctxt)))
                goto error;
            if (xenXMConfigSetString(conf, "soundhw", soundstr) < 0) {
2282
                VIR_FREE(soundstr);
D
Daniel Veillard 已提交
2283 2284
                goto error;
            }
2285
            VIR_FREE(soundstr);
D
Daniel Veillard 已提交
2286
        }
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
    }

    xmlFreeDoc(doc);
    xmlXPathFreeContext(ctxt);

    return conf;

 error:
    if (conf)
        virConfFree(conf);
2297
    xmlFree(prop);
2298
    xmlXPathFreeObject(obj);
2299
    xmlXPathFreeContext(ctxt);
2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310
    if (doc != NULL)
        xmlFreeDoc(doc);
    return (NULL);
}

/*
 * Create a config file for a domain, based on an XML
 * document describing its config
 */
virDomainPtr xenXMDomainDefineXML(virConnectPtr conn, const char *xml) {
    virDomainPtr ret;
2311
    virDomainPtr olddomain;
2312
    char filename[PATH_MAX];
2313
    const char * oldfilename;
2314
    virDomainDefPtr def = NULL;
2315
    xenXMConfCachePtr entry = NULL;
2316
    xenUnifiedPrivatePtr priv = (xenUnifiedPrivatePtr) conn->privateData;
2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328

    if (!VIR_IS_CONNECT(conn)) {
        xenXMError(conn, VIR_ERR_INVALID_CONN, __FUNCTION__);
        return (NULL);
    }
    if (xml == NULL) {
        xenXMError(conn, VIR_ERR_INVALID_ARG, __FUNCTION__);
        return (NULL);
    }
    if (conn->flags & VIR_CONNECT_RO)
        return (NULL);

2329
    if (xenXMConfigCacheRefresh (conn) < 0)
2330 2331
        return (NULL);

2332 2333
    if (!(def = virDomainDefParseString(conn, priv->caps, xml)))
        return (NULL);
2334

2335
    if (virHashLookup(nameConfigMap, def->name)) {
2336 2337
        /* domain exists, we will overwrite it */

2338
        if (!(oldfilename = (char *)virHashLookup(nameConfigMap, def->name))) {
2339 2340
            xenXMError(conn, VIR_ERR_INTERNAL_ERROR,
                       _("can't retrieve config filename for domain to overwrite"));
2341 2342 2343 2344
            goto error;
        }

        if (!(entry = virHashLookup(configCache, oldfilename))) {
2345 2346
            xenXMError(conn, VIR_ERR_INTERNAL_ERROR,
                       _("can't retrieve config entry for domain to overwrite"));
2347 2348 2349
            goto error;
        }

2350 2351
        /* XXX wtf.com is this line for - it appears to be amemory leak */
        if (!(olddomain = virGetDomain(conn, def->name, entry->def->uuid)))
2352 2353 2354
            goto error;

        /* Remove the name -> filename mapping */
2355
        if (virHashRemoveEntry(nameConfigMap, def->name, NULL) < 0) {
2356 2357
            xenXMError(conn, VIR_ERR_INTERNAL_ERROR,
                       _("failed to remove old domain from config map"));
2358 2359 2360 2361 2362
            goto error;
        }

        /* Remove the config record itself */
        if (virHashRemoveEntry(configCache, oldfilename, xenXMConfigFree) < 0) {
2363 2364
            xenXMError(conn, VIR_ERR_INTERNAL_ERROR,
                       _("failed to remove old domain from config map"));
2365 2366 2367 2368
            goto error;
        }

        entry = NULL;
2369
    }
2370

2371
    if ((strlen(configDir) + 1 + strlen(def->name) + 1) > PATH_MAX) {
2372 2373
        xenXMError(conn, VIR_ERR_INTERNAL_ERROR,
                   _("config file name is too long"));
2374
        goto error;
2375
    }
2376 2377 2378

    strcpy(filename, configDir);
    strcat(filename, "/");
2379
    strcat(filename, def->name);
2380

2381
    if (xenXMConfigSaveFile(conn, filename, def) < 0)
2382 2383
        goto error;

2384
    if (VIR_ALLOC(entry) < 0) {
2385
        xenXMError(conn, VIR_ERR_NO_MEMORY, _("config"));
2386
        goto error;
2387
    }
2388

2389
    if ((entry->refreshedAt = time(NULL)) == ((time_t)-1)) {
2390 2391
        xenXMError(conn, VIR_ERR_INTERNAL_ERROR,
                   _("unable to get current time"));
2392
        goto error;
2393
    }
2394 2395

    memmove(entry->filename, filename, PATH_MAX);
2396
    entry->def = def;
2397

2398
    if (virHashAddEntry(configCache, filename, entry) < 0) {
2399 2400
        xenXMError(conn, VIR_ERR_INTERNAL_ERROR,
                   _("unable to store config file handle"));
2401
        goto error;
2402
    }
2403

2404
    if (virHashAddEntry(nameConfigMap, def->name, entry->filename) < 0) {
2405
        virHashRemoveEntry(configCache, filename, NULL);
2406 2407
        xenXMError(conn, VIR_ERR_INTERNAL_ERROR,
                   _("unable to store config file handle"));
2408
        goto error;
2409 2410
    }

2411 2412
    if (!(ret = virGetDomain(conn, def->name, def->uuid)))
        return NULL;
2413

2414
    ret->id = -1;
2415 2416 2417 2418

    return (ret);

 error:
2419
    VIR_FREE(entry);
2420
    virDomainDefFree(def);
2421 2422 2423 2424 2425 2426 2427
    return (NULL);
}

/*
 * Delete a domain from disk
 */
int xenXMDomainUndefine(virDomainPtr domain) {
2428
    const char *filename;
2429 2430 2431 2432 2433 2434 2435
    xenXMConfCachePtr entry;
    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
        xenXMError((domain ? domain->conn : NULL), VIR_ERR_INVALID_ARG,
                   __FUNCTION__);
        return (-1);
    }

2436
    if (domain->id != -1)
2437 2438 2439 2440
        return (-1);
    if (domain->conn->flags & VIR_CONNECT_RO)
        return (-1);

2441 2442 2443 2444
    if (!(filename = virHashLookup(nameConfigMap, domain->name)))
        return (-1);

    if (!(entry = virHashLookup(configCache, filename)))
2445 2446 2447 2448 2449
        return (-1);

    if (unlink(entry->filename) < 0)
        return (-1);

2450 2451
    /* Remove the name -> filename mapping */
    if (virHashRemoveEntry(nameConfigMap, domain->name, NULL) < 0)
2452 2453
        return(-1);

2454 2455
    /* Remove the config record itself */
    if (virHashRemoveEntry(configCache, entry->filename, xenXMConfigFree) < 0)
2456 2457 2458 2459 2460 2461 2462 2463 2464
        return (-1);

    return (0);
}

struct xenXMListIteratorContext {
    virConnectPtr conn;
    int max;
    int count;
2465
    char ** names;
2466 2467 2468 2469 2470 2471 2472 2473 2474
};

static void xenXMListIterator(const void *payload ATTRIBUTE_UNUSED, const char *name, const void *data) {
    struct xenXMListIteratorContext *ctx = (struct xenXMListIteratorContext *)data;
    virDomainPtr dom = NULL;

    if (ctx->count == ctx->max)
        return;

2475
    dom = xenDaemonLookupByName(ctx->conn, name);
2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488
    if (!dom) {
        ctx->names[ctx->count] = strdup(name);
        ctx->count++;
    } else {
        virDomainFree(dom);
    }
}


/*
 * List all defined domains, filtered to remove any which
 * are currently running
 */
2489
int xenXMListDefinedDomains(virConnectPtr conn, char **const names, int maxnames) {
2490 2491 2492 2493 2494 2495 2496
    struct xenXMListIteratorContext ctx;

    if (!VIR_IS_CONNECT(conn)) {
        xenXMError(conn, VIR_ERR_INVALID_CONN, __FUNCTION__);
        return (-1);
    }

2497
    if (xenXMConfigCacheRefresh (conn) < 0)
2498 2499 2500 2501 2502 2503 2504 2505 2506 2507
        return (-1);

    if (maxnames > virHashSize(configCache))
        maxnames = virHashSize(configCache);

    ctx.conn = conn;
    ctx.count = 0;
    ctx.max = maxnames;
    ctx.names = names;

2508
    virHashForEach(nameConfigMap, xenXMListIterator, &ctx);
2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521
    return (ctx.count);
}

/*
 * Return the maximum number of defined domains - not filtered
 * based on number running
 */
int xenXMNumOfDefinedDomains(virConnectPtr conn) {
    if (!VIR_IS_CONNECT(conn)) {
        xenXMError(conn, VIR_ERR_INVALID_CONN, __FUNCTION__);
        return (-1);
    }

2522
    if (xenXMConfigCacheRefresh (conn) < 0)
2523 2524
        return (-1);

2525
    return virHashSize(nameConfigMap);
2526 2527
}

2528 2529 2530 2531 2532 2533 2534 2535 2536
static int xenXMDiskCompare(virDomainDiskDefPtr a,
                            virDomainDiskDefPtr b) {
    if (a->bus == b->bus)
        return virDiskNameToIndex(a->dst) - virDiskNameToIndex(b->dst);
    else
        return a->bus - b->bus;
}


2537 2538 2539 2540
/**
 * xenXMDomainAttachDevice:
 * @domain: pointer to domain object
 * @xml: pointer to XML description of device
J
Jim Meyering 已提交
2541
 *
2542 2543
 * Create a virtual device attachment to backend.
 * XML description is translated into config file.
J
Jim Meyering 已提交
2544
 *
2545 2546 2547 2548 2549 2550
 * Returns 0 in case of success, -1 in case of failure.
 */
static int
xenXMDomainAttachDevice(virDomainPtr domain, const char *xml) {
    const char *filename = NULL;
    xenXMConfCachePtr entry = NULL;
2551 2552
    int ret = -1;
    virDomainDeviceDefPtr dev = NULL;
2553 2554 2555 2556

    if ((!domain) || (!domain->conn) || (!domain->name) || (!xml)) {
        xenXMError((domain ? domain->conn : NULL), VIR_ERR_INVALID_ARG,
                   __FUNCTION__);
2557
        return -1;
2558 2559
    }
    if (domain->conn->flags & VIR_CONNECT_RO)
2560
        return -1;
2561
    if (domain->id != -1)
2562 2563
        return -1;

2564
    if (!(filename = virHashLookup(nameConfigMap, domain->name)))
2565
        return -1;
2566
    if (!(entry = virHashLookup(configCache, filename)))
2567
        return -1;
2568

2569 2570 2571 2572
    if (!(dev = virDomainDeviceDefParse(domain->conn,
                                        entry->def,
                                        xml)))
        return -1;
2573

2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592
    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
    {
        /* Maintain list in sorted order according to target device name */
        if (entry->def->disks == NULL) {
            dev->data.disk->next = entry->def->disks;
            entry->def->disks = dev->data.disk;
        } else {
            virDomainDiskDefPtr ptr = entry->def->disks;
            while (ptr) {
                if (!ptr->next || xenXMDiskCompare(dev->data.disk, ptr->next) < 0) {
                    dev->data.disk->next = ptr->next;
                    ptr->next = dev->data.disk;
                    break;
                }
                ptr = ptr->next;
            }
        }
        dev->data.disk = NULL;
2593
    }
2594
    break;
2595

2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606
    case VIR_DOMAIN_DEVICE_NET:
    {
        virDomainNetDefPtr net = entry->def->nets;
        while (net && net->next)
            net = net->next;
        if (net)
            net->next = dev->data.net;
        else
            entry->def->nets = dev->data.net;
        dev->data.net = NULL;
        break;
2607 2608
    }

2609
    default:
2610 2611
        xenXMError(domain->conn, VIR_ERR_XML_ERROR,
                   _("unknown device"));
2612 2613 2614 2615 2616 2617
        goto cleanup;
    }

    /* If this fails, should we try to undo our changes to the
     * in-memory representation of the config file. I say not!
     */
2618
    if (xenXMConfigSaveFile(domain->conn, entry->filename, entry->def) < 0)
2619 2620 2621 2622 2623
        goto cleanup;

    ret = 0;

 cleanup:
2624
    virDomainDeviceDefFree(dev);
2625 2626 2627 2628 2629 2630 2631 2632

    return ret;
}


/**
 * xenXMAutoAssignMac:
 * @mac: pointer to Mac String
J
Jim Meyering 已提交
2633
 *
2634 2635 2636 2637 2638 2639 2640 2641
 * a mac is assigned automatically.
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
char *
xenXMAutoAssignMac() {
    char *buf;

2642
    if (VIR_ALLOC_N(buf, 18) < 0)
2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655
        return 0;
    srand((unsigned)time(NULL));
    sprintf(buf, "00:16:3e:%02x:%02x:%02x"
            ,1 + (int)(256*(rand()/(RAND_MAX+1.0)))
            ,1 + (int)(256*(rand()/(RAND_MAX+1.0)))
            ,1 + (int)(256*(rand()/(RAND_MAX+1.0))));
    return buf;
}

/**
 * xenXMDomainDetachDevice:
 * @domain: pointer to domain object
 * @xml: pointer to XML description of device
J
Jim Meyering 已提交
2656
 *
2657 2658 2659 2660 2661 2662 2663 2664
 * Destroy a virtual device attachment to backend.
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
static int
xenXMDomainDetachDevice(virDomainPtr domain, const char *xml) {
    const char *filename = NULL;
    xenXMConfCachePtr entry = NULL;
2665
    virDomainDeviceDefPtr dev = NULL;
2666 2667 2668 2669 2670
    int ret = -1;

    if ((!domain) || (!domain->conn) || (!domain->name) || (!xml)) {
        xenXMError((domain ? domain->conn : NULL), VIR_ERR_INVALID_ARG,
                   __FUNCTION__);
2671
        return -1;
2672 2673
    }
    if (domain->conn->flags & VIR_CONNECT_RO)
2674
        return -1;
2675
    if (domain->id != -1)
2676
        return -1;
2677
    if (!(filename = virHashLookup(nameConfigMap, domain->name)))
2678
        return -1;
2679
    if (!(entry = virHashLookup(configCache, filename)))
2680
        return -1;
2681

2682 2683 2684 2685
    if (!(dev = virDomainDeviceDefParse(domain->conn,
                                        entry->def,
                                        xml)))
        return -1;
2686

2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699
    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
    {
        virDomainDiskDefPtr disk = entry->def->disks;
        virDomainDiskDefPtr prev = NULL;
        while (disk) {
            if (disk->dst &&
                dev->data.disk->dst &&
                STREQ(disk->dst, dev->data.disk->dst)) {
                if (prev) {
                    prev->next = disk->next;
                } else {
                    entry->def->disks = disk->next;
2700
                }
2701 2702
                virDomainDiskDefFree(disk);
                break;
2703
            }
2704 2705
            prev = disk;
            disk = disk->next;
2706
        }
2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727
        break;
    }

    case VIR_DOMAIN_DEVICE_NET:
    {
        virDomainNetDefPtr net = entry->def->nets;
        virDomainNetDefPtr prev = NULL;
        while (net) {
            if (!memcmp(net->mac, dev->data.net->mac, VIR_DOMAIN_NET_MAC_SIZE)) {
                if (prev) {
                    prev->next = net->next;
                } else {
                    entry->def->nets = net->next;
                }
                virDomainNetDefFree(net);
                break;
            }
            prev = net;
            net = net->next;
        }
        break;
2728
    }
2729 2730 2731
    default:
        xenXMError(domain->conn, VIR_ERR_XML_ERROR,
                   _("unknown device"));
2732 2733 2734 2735 2736 2737
        goto cleanup;
    }

    /* If this fails, should we try to undo our changes to the
     * in-memory representation of the config file. I say not!
     */
2738
    if (xenXMConfigSaveFile(domain->conn, entry->filename, entry->def) < 0)
2739 2740 2741 2742 2743
        goto cleanup;

    ret = 0;

 cleanup:
2744
    virDomainDeviceDefFree(dev);
2745 2746 2747
    return (ret);
}

R
Richard W.M. Jones 已提交
2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758
int
xenXMDomainBlockPeek (virDomainPtr dom,
                      const char *path ATTRIBUTE_UNUSED,
                      unsigned long long offset ATTRIBUTE_UNUSED,
                      size_t size ATTRIBUTE_UNUSED,
                      void *buffer ATTRIBUTE_UNUSED)
{
    xenXMError (dom->conn, VIR_ERR_NO_SUPPORT, __FUNCTION__);
    return -1;
}

2759
#endif /* WITH_XEN */