xm_internal.c 45.5 KB
Newer Older
1 2 3
/*
 * xm_internal.h: helper routines for dealing with inactive domains
 *
4
 * Copyright (C) 2006-2007, 2009-2011 Red Hat, Inc.
5
 * 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
#include <config.h>
26

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

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

38
#include "virterror_internal.h"
39
#include "datatypes.h"
40
#include "xm_internal.h"
41
#include "xen_driver.h"
42
#include "xend_internal.h"
43
#include "xen_sxpr.h"
44
#include "xen_xm.h"
45
#include "hash.h"
46
#include "buf.h"
47
#include "uuid.h"
48
#include "util.h"
49
#include "memory.h"
50
#include "logging.h"
51
#include "count-one-bits.h"
52

53
#define VIR_FROM_THIS VIR_FROM_XENXM
54

55
#ifdef WITH_RHEL5_API
56 57
# define XEND_CONFIG_MAX_VERS_NET_TYPE_IOEMU 0
# define XEND_CONFIG_MIN_VERS_PVFB_NEWCONF 2
58
#else
59 60
# define XEND_CONFIG_MAX_VERS_NET_TYPE_IOEMU 3
# define XEND_CONFIG_MIN_VERS_PVFB_NEWCONF 3
61 62
#endif

63 64 65 66 67
/* 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

68
char * xenXMAutoAssignMac(void);
69 70 71 72
static int xenXMDomainAttachDeviceFlags(virDomainPtr domain, const char *xml,
                                        unsigned int flags);
static int xenXMDomainDetachDeviceFlags(virDomainPtr domain, const char *xml,
                                        unsigned int flags);
73

74 75 76 77 78 79 80
#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"
81
#define XM_XML_ERROR "Invalid xml"
82

83
struct xenUnifiedDriver xenXMDriver = {
E
Eric Blake 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96
    .xenClose = xenXMClose,
    .xenDomainGetMaxMemory = xenXMDomainGetMaxMemory,
    .xenDomainSetMaxMemory = xenXMDomainSetMaxMemory,
    .xenDomainSetMemory = xenXMDomainSetMemory,
    .xenDomainGetInfo = xenXMDomainGetInfo,
    .xenDomainPinVcpu = xenXMDomainPinVcpu,
    .xenListDefinedDomains = xenXMListDefinedDomains,
    .xenNumOfDefinedDomains = xenXMNumOfDefinedDomains,
    .xenDomainCreate = xenXMDomainCreate,
    .xenDomainDefineXML = xenXMDomainDefineXML,
    .xenDomainUndefine = xenXMDomainUndefine,
    .xenDomainAttachDeviceFlags = xenXMDomainAttachDeviceFlags,
    .xenDomainDetachDeviceFlags = xenXMDomainDetachDeviceFlags,
97 98
};

99
#define xenXMError(code, ...)                                              \
100
        virReportErrorHelper(VIR_FROM_XENXM, code, __FILE__,               \
101
                             __FUNCTION__, __LINE__, __VA_ARGS__)
102

103
#ifndef WITH_XEN_INOTIFY
104 105 106 107
static int xenInotifyActive(virConnectPtr conn ATTRIBUTE_UNUSED)
{
   return 0;
}
108
#else
109 110 111 112
static int xenInotifyActive(virConnectPtr conn)
{
   xenUnifiedPrivatePtr priv = (xenUnifiedPrivatePtr) conn->privateData;
   return priv->inotifyWatch > 0;
113
}
114
#endif
115

116 117

/* Release memory associated with a cached config object */
118
static void xenXMConfigFree(void *payload, const void *key ATTRIBUTE_UNUSED) {
119
    xenXMConfCachePtr entry = (xenXMConfCachePtr)payload;
120
    virDomainDefFree(entry->def);
E
Eric Blake 已提交
121
    VIR_FREE(entry->filename);
122
    VIR_FREE(entry);
123 124
}

125 126 127 128
struct xenXMConfigReaperData {
    xenUnifiedPrivatePtr priv;
    time_t now;
};
129

130
/* Remove any configs which were not refreshed recently */
131
static int xenXMConfigReaper(const void *payload, const void *key ATTRIBUTE_UNUSED, const void *data) {
132
    const struct xenXMConfigReaperData *args = data;
133 134
    xenXMConfCachePtr entry = (xenXMConfCachePtr)payload;

135 136
    /* We're going to purge this config file, so check if it
       is currently mapped as owner of a named domain. */
137
    if (entry->refreshedAt != args->now) {
138
        const char *olddomname = entry->def->name;
139
        char *nameowner = (char *)virHashLookup(args->priv->nameConfigMap, olddomname);
140
        if (nameowner && STREQ(nameowner, key)) {
141
            virHashRemoveEntry(args->priv->nameConfigMap, olddomname);
142 143 144 145 146 147
        }
        return (1);
    }
    return (0);
}

148 149 150 151 152

static virDomainDefPtr
xenXMConfigReadFile(virConnectPtr conn, const char *filename) {
    virConfPtr conf;
    virDomainDefPtr def;
153
    xenUnifiedPrivatePtr priv = conn->privateData;
154

155
    if (!(conf = virConfReadFile(filename, 0)))
156 157
        return NULL;

M
Markus Groß 已提交
158
    def = xenParseXM(conf, priv->xendConfigVersion, priv->caps);
159 160 161 162 163 164 165 166
    virConfFree(conf);

    return def;
}

static int
xenXMConfigSaveFile(virConnectPtr conn, const char *filename, virDomainDefPtr def) {
    virConfPtr conf;
167
    xenUnifiedPrivatePtr priv = conn->privateData;
168 169
    int ret;

M
Markus Groß 已提交
170
    if (!(conf = xenFormatXM(conn, def, priv->xendConfigVersion)))
171 172 173 174 175 176 177
        return -1;

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

D
Daniel P. Berrange 已提交
178 179 180 181 182

/*
 * Caller must hold the lock on 'conn->privateData' before
 * calling this funtion
 */
183
int
184
xenXMConfigCacheRemoveFile(virConnectPtr conn,
185 186
                           const char *filename)
{
187
    xenUnifiedPrivatePtr priv = conn->privateData;
188 189
    xenXMConfCachePtr entry;

190
    entry = virHashLookup(priv->configCache, filename);
191
    if (!entry) {
192
        VIR_DEBUG("No config entry for %s", filename);
193 194 195
        return 0;
    }

196 197
    virHashRemoveEntry(priv->nameConfigMap, entry->def->name);
    virHashRemoveEntry(priv->configCache, filename);
198
    VIR_DEBUG("Removed %s %s", entry->def->name, filename);
199 200 201 202
    return 0;
}


D
Daniel P. Berrange 已提交
203 204 205 206
/*
 * Caller must hold the lock on 'conn->privateData' before
 * calling this funtion
 */
207 208 209
int
xenXMConfigCacheAddFile(virConnectPtr conn, const char *filename)
{
210
    xenUnifiedPrivatePtr priv = conn->privateData;
211 212 213 214 215
    xenXMConfCachePtr entry;
    struct stat st;
    int newborn = 0;
    time_t now = time(NULL);

216
    VIR_DEBUG("Adding file %s", filename);
217 218 219

    /* Get modified time */
    if ((stat(filename, &st) < 0)) {
220
        virReportSystemError(errno,
221 222
                             _("cannot stat: %s"),
                             filename);
223 224 225 226 227 228
        return -1;
    }

    /* Ignore zero length files, because inotify fires before
       any content has actually been created */
    if (st.st_size == 0) {
229
        VIR_DEBUG("Ignoring zero length file %s", filename);
230 231 232 233 234
        return -1;
    }

    /* If we already have a matching entry and it is not
    modified, then carry on to next one*/
235
    if ((entry = virHashLookup(priv->configCache, filename))) {
236 237 238 239 240 241 242 243 244 245
        char *nameowner;

        if (entry->refreshedAt >= st.st_mtime) {
            entry->refreshedAt = now;
            /* return success if up-to-date */
            return 0;
        }

        /* If we currently own the name, then release it and
            re-acquire it later - just in case it was renamed */
246
        nameowner = (char *)virHashLookup(priv->nameConfigMap, entry->def->name);
247
        if (nameowner && STREQ(nameowner, filename)) {
248
            virHashRemoveEntry(priv->nameConfigMap, entry->def->name);
249 250 251 252 253 254 255 256
        }

        /* Clear existing config entry which needs refresh */
        virDomainDefFree(entry->def);
        entry->def = NULL;
    } else { /* Completely new entry */
        newborn = 1;
        if (VIR_ALLOC(entry) < 0) {
257
            virReportOOMError();
258 259
            return -1;
        }
E
Eric Blake 已提交
260 261 262 263 264
        if ((entry->filename = strdup(filename)) == NULL) {
            virReportOOMError();
            VIR_FREE(entry);
            return -1;
        }
265 266 267 268
    }
    entry->refreshedAt = now;

    if (!(entry->def = xenXMConfigReadFile(conn, entry->filename))) {
269
        VIR_DEBUG("Failed to read %s", entry->filename);
270
        if (!newborn)
271
            virHashSteal(priv->configCache, filename);
E
Eric Blake 已提交
272
        VIR_FREE(entry->filename);
273 274 275 276 277 278 279
        VIR_FREE(entry);
        return -1;
    }

    /* If its a completely new entry, it must be stuck into
        the cache (refresh'd entries are already registered) */
    if (newborn) {
280
        if (virHashAddEntry(priv->configCache, entry->filename, entry) < 0) {
281
            virDomainDefFree(entry->def);
E
Eric Blake 已提交
282
            VIR_FREE(entry->filename);
283
            VIR_FREE(entry);
284
            xenXMError(VIR_ERR_INTERNAL_ERROR,
285 286 287 288 289 290 291 292
                        "%s", _("xenXMConfigCacheRefresh: virHashAddEntry"));
            return -1;
        }
    }

    /* See if we need to map this config file in as the primary owner
        * of the domain in question
        */
293
    if (!virHashLookup(priv->nameConfigMap, entry->def->name)) {
E
Eric Blake 已提交
294 295
        if (virHashAddEntry(priv->nameConfigMap, entry->def->name,
                            entry->filename) < 0) {
296
            virHashSteal(priv->configCache, filename);
297
            virDomainDefFree(entry->def);
E
Eric Blake 已提交
298
            VIR_FREE(entry->filename);
299 300 301
            VIR_FREE(entry);
        }
    }
302
    VIR_DEBUG("Added config %s %s", entry->def->name, filename);
303 304 305

    return 0;
}
306

307
/* This method is called by various methods to scan /etc/xen
D
Daniel P. Berrange 已提交
308 309 310 311 312 313 314 315
 * (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
 *
 * Caller must hold the lock on 'conn->privateData' before
 * calling this funtion
 */
316
int xenXMConfigCacheRefresh (virConnectPtr conn) {
317
    xenUnifiedPrivatePtr priv = conn->privateData;
318 319 320 321
    DIR *dh;
    struct dirent *ent;
    time_t now = time(NULL);
    int ret = -1;
322
    struct xenXMConfigReaperData args;
323 324

    if (now == ((time_t)-1)) {
325
        virReportSystemError(errno,
326
                             "%s", _("cannot get time of day"));
327 328 329 330
        return (-1);
    }

    /* Rate limit re-scans */
331
    if ((now - priv->lastRefresh) < XM_REFRESH_INTERVAL)
332 333
        return (0);

334
    priv->lastRefresh = now;
335 336

    /* Process the files in the config dir */
337
    if (!(dh = opendir(priv->configDir))) {
338
        virReportSystemError(errno,
339
                             _("cannot read directory %s"),
340
                             priv->configDir);
341 342 343 344 345
        return (-1);
    }

    while ((ent = readdir(dh))) {
        struct stat st;
346
        char *path;
347 348 349 350 351 352

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

        /* Like 'dot' files... */
353
        if (STRPREFIX(ent->d_name, "."))
354 355
            continue;
        /* ...and the XenD server config file */
356
        if (STRPREFIX(ent->d_name, XEND_CONFIG_FILE))
357 358
            continue;
        /* ...and random PCI config cruft */
359
        if (STRPREFIX(ent->d_name, XEND_PCI_CONFIG_PREFIX))
360 361
            continue;
        /* ...and the example domain configs */
362
        if (STRPREFIX(ent->d_name, XM_EXAMPLE_PREFIX))
363 364
            continue;
        /* ...and the QEMU networking script */
365
        if (STRPREFIX(ent->d_name, QEMU_IF_SCRIPT))
366 367 368 369 370 371 372 373 374
            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 */
375 376 377 378
        if (!(path = virFileBuildPath(priv->configDir, ent->d_name, NULL))) {
            closedir(dh);
            return -1;
        }
379 380 381 382

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

        /* If we already have a matching entry and it is not
           modified, then carry on to next one*/
389 390
        if (xenXMConfigCacheAddFile(conn, path) < 0) {
            /* Ignoring errors, since alot of stuff goes wrong in /etc/xen */
391
        }
392 393

        VIR_FREE(path);
394 395 396 397 398 399
    }

    /* 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 */
400 401
    args.now = now;
    args.priv = priv;
402
    virHashRemoveSet(priv->configCache, xenXMConfigReaper, &args);
403 404
    ret = 0;

405
    closedir(dh);
406 407 408 409 410 411

    return (ret);
}


/*
412 413 414 415
 * The XM driver keeps a cache of config files as virDomainDefPtr
 * objects in the xenUnifiedPrivatePtr. Optionally inotify lets
 * us watch for changes (see separate driver), otherwise we poll
 * every few seconds
416
 */
417
virDrvOpenStatus
418
xenXMOpen (virConnectPtr conn,
419
           virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
420
           unsigned int flags)
421
{
422 423
    xenUnifiedPrivatePtr priv = conn->privateData;

E
Eric Blake 已提交
424 425
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

426 427
    priv->configDir = XM_CONFIG_DIR;

428
    priv->configCache = virHashCreate(50, xenXMConfigFree);
429 430
    if (!priv->configCache)
        return (-1);
431
    priv->nameConfigMap = virHashCreate(50, NULL);
432
    if (!priv->nameConfigMap) {
433
        virHashFree(priv->configCache);
434 435
        priv->configCache = NULL;
        return (-1);
436
    }
437 438 439 440
    /* Force the cache to be reloaded next time that
     * xenXMConfigCacheRefresh is called.
     */
    priv->lastRefresh = 0;
441 442 443 444 445

    return (0);
}

/*
446 447
 * Free the cached config files associated with this
 * connection
448
 */
449 450 451
int xenXMClose(virConnectPtr conn) {
    xenUnifiedPrivatePtr priv = conn->privateData;

452 453
    virHashFree(priv->nameConfigMap);
    virHashFree(priv->configCache);
454

455 456 457
    return (0);
}

458 459 460 461 462 463 464
/*
 * Since these are all offline domains, the state is always SHUTOFF.
 */
int
xenXMDomainGetState(virDomainPtr domain,
                    int *state,
                    int *reason,
E
Eric Blake 已提交
465
                    unsigned int flags)
466
{
E
Eric Blake 已提交
467 468
    virCheckFlags(0, -1);

469 470 471 472 473 474 475 476 477 478 479
    if (domain->id != -1)
        return -1;

    *state = VIR_DOMAIN_SHUTOFF;
    if (reason)
        *reason = 0;

    return 0;
}


480 481
/*
 * Since these are all offline domains, we only return info about
482
 * VCPUs and memory.
483 484
 */
int xenXMDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info) {
485
    xenUnifiedPrivatePtr priv;
486
    const char *filename;
487 488
    xenXMConfCachePtr entry;
    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
489
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
490 491 492
        return(-1);
    }

493
    if (domain->id != -1)
494 495
        return (-1);

496
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
497
    xenUnifiedLock(priv);
498 499

    if (!(filename = virHashLookup(priv->nameConfigMap, domain->name)))
D
Daniel P. Berrange 已提交
500
        goto error;
501

502
    if (!(entry = virHashLookup(priv->configCache, filename)))
D
Daniel P. Berrange 已提交
503
        goto error;
504 505

    memset(info, 0, sizeof(virDomainInfo));
506 507
    info->maxMem = entry->def->mem.max_balloon;
    info->memory = entry->def->mem.cur_balloon;
508
    info->nrVirtCpu = entry->def->vcpus;
509 510 511
    info->state = VIR_DOMAIN_SHUTOFF;
    info->cpuTime = 0;

D
Daniel P. Berrange 已提交
512
    xenUnifiedUnlock(priv);
513 514
    return (0);

D
Daniel P. Berrange 已提交
515 516 517
error:
    xenUnifiedUnlock(priv);
    return -1;
518 519 520
}


521 522
/*
 * Turn a config record into a lump of XML describing the
523
 * domain, suitable for later feeding for virDomainCreateXML
524
 */
E
Eric Blake 已提交
525 526
char *xenXMDomainGetXMLDesc(virDomainPtr domain, unsigned int flags)
{
527
    xenUnifiedPrivatePtr priv;
528 529
    const char *filename;
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
530
    char *ret = NULL;
531

E
Eric Blake 已提交
532 533
    /* Flags checked by virDomainDefFormat */

534
    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
535
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
536 537
        return(NULL);
    }
538
    if (domain->id != -1)
539 540
        return (NULL);

541
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
542
    xenUnifiedLock(priv);
543 544

    if (!(filename = virHashLookup(priv->nameConfigMap, domain->name)))
D
Daniel P. Berrange 已提交
545
        goto cleanup;
546

547
    if (!(entry = virHashLookup(priv->configCache, filename)))
D
Daniel P. Berrange 已提交
548 549
        goto cleanup;

550
    ret = virDomainDefFormat(entry->def, flags);
551

D
Daniel P. Berrange 已提交
552 553 554
cleanup:
    xenUnifiedUnlock(priv);
    return ret;
555 556 557
}


558 559 560 561
/*
 * Update amount of memory in the config file
 */
int xenXMDomainSetMemory(virDomainPtr domain, unsigned long memory) {
562
    xenUnifiedPrivatePtr priv;
563
    const char *filename;
564
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
565
    int ret = -1;
566 567

    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
568
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
569 570 571 572
        return (-1);
    }
    if (domain->conn->flags & VIR_CONNECT_RO)
        return (-1);
573
    if (domain->id != -1)
574
        return (-1);
575 576
    if (memory < 1024 * MIN_XEN_GUEST_SIZE)
        return (-1);
577

578
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
579
    xenUnifiedLock(priv);
580 581

    if (!(filename = virHashLookup(priv->nameConfigMap, domain->name)))
D
Daniel P. Berrange 已提交
582
        goto cleanup;
583

584
    if (!(entry = virHashLookup(priv->configCache, filename)))
D
Daniel P. Berrange 已提交
585
        goto cleanup;
586

587 588 589
    entry->def->mem.cur_balloon = memory;
    if (entry->def->mem.cur_balloon > entry->def->mem.max_balloon)
        entry->def->mem.cur_balloon = entry->def->mem.max_balloon;
590 591 592 593

    /* If this fails, should we try to undo our changes to the
     * in-memory representation of the config file. I say not!
     */
594
    if (xenXMConfigSaveFile(domain->conn, entry->filename, entry->def) < 0)
D
Daniel P. Berrange 已提交
595 596
        goto cleanup;
    ret = 0;
597

D
Daniel P. Berrange 已提交
598 599 600
cleanup:
    xenUnifiedUnlock(priv);
    return ret;
601 602 603 604 605 606
}

/*
 * Update maximum memory limit in config
 */
int xenXMDomainSetMaxMemory(virDomainPtr domain, unsigned long memory) {
607
    xenUnifiedPrivatePtr priv;
608
    const char *filename;
609
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
610
    int ret = -1;
611 612

    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
613
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
614 615 616 617
        return (-1);
    }
    if (domain->conn->flags & VIR_CONNECT_RO)
        return (-1);
618
    if (domain->id != -1)
619 620
        return (-1);

621
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
622
    xenUnifiedLock(priv);
623 624

    if (!(filename = virHashLookup(priv->nameConfigMap, domain->name)))
D
Daniel P. Berrange 已提交
625
        goto cleanup;
626

627
    if (!(entry = virHashLookup(priv->configCache, filename)))
D
Daniel P. Berrange 已提交
628
        goto cleanup;
629

630 631 632
    entry->def->mem.max_balloon = memory;
    if (entry->def->mem.cur_balloon > entry->def->mem.max_balloon)
        entry->def->mem.cur_balloon = entry->def->mem.max_balloon;
633 634 635 636

    /* If this fails, should we try to undo our changes to the
     * in-memory representation of the config file. I say not!
     */
637
    if (xenXMConfigSaveFile(domain->conn, entry->filename, entry->def) < 0)
D
Daniel P. Berrange 已提交
638 639
        goto cleanup;
    ret = 0;
640

D
Daniel P. Berrange 已提交
641 642 643
cleanup:
    xenUnifiedUnlock(priv);
    return ret;
644 645 646 647 648 649
}

/*
 * Get max memory limit from config
 */
unsigned long xenXMDomainGetMaxMemory(virDomainPtr domain) {
650
    xenUnifiedPrivatePtr priv;
651
    const char *filename;
652
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
653
    unsigned long ret = 0;
654 655

    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
656
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
D
Daniel P. Berrange 已提交
657
        return (0);
658
    }
659
    if (domain->id != -1)
D
Daniel P. Berrange 已提交
660
        return (0);
661

662
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
663
    xenUnifiedLock(priv);
664 665

    if (!(filename = virHashLookup(priv->nameConfigMap, domain->name)))
D
Daniel P. Berrange 已提交
666
        goto cleanup;
667

668
    if (!(entry = virHashLookup(priv->configCache, filename)))
D
Daniel P. Berrange 已提交
669 670
        goto cleanup;

671
    ret = entry->def->mem.max_balloon;
672

D
Daniel P. Berrange 已提交
673 674 675
cleanup:
    xenUnifiedUnlock(priv);
    return ret;
676 677
}

678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
/*
 * xenXMDomainSetVcpusFlags:
 * @domain: pointer to domain object
 * @nvcpus: number of vcpus
 * @flags: bitwise-ORd from virDomainVcpuFlags
 *
 * Change virtual CPUs allocation of domain according to flags.
 *
 * Returns 0 on success, -1 if an error message was issued, and -2 if
 * the unified driver should keep trying.
 */
int
xenXMDomainSetVcpusFlags(virDomainPtr domain, unsigned int vcpus,
                         unsigned int flags)
{
    xenUnifiedPrivatePtr priv;
    const char *filename;
    xenXMConfCachePtr entry;
    int ret = -1;
    int max;

E
Eric Blake 已提交
699 700 701 702
    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
                  VIR_DOMAIN_VCPU_CONFIG |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
        return -1;
    }
    if (domain->conn->flags & VIR_CONNECT_RO) {
        xenXMError(VIR_ERR_OPERATION_DENIED, __FUNCTION__);
        return -1;
    }
    if (domain->id != -1)
        return -2;
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
        xenXMError(VIR_ERR_OPERATION_INVALID, "%s",
                   _("domain is not running"));
        return -1;
    }

    priv = domain->conn->privateData;
    xenUnifiedLock(priv);

    if (!(filename = virHashLookup(priv->nameConfigMap, domain->name)))
        goto cleanup;

    if (!(entry = virHashLookup(priv->configCache, filename)))
        goto cleanup;

    /* Hypervisor maximum. */
    if ((max = xenUnifiedGetMaxVcpus(domain->conn, NULL)) < 0) {
        xenXMError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("could not determin max vcpus for the domain"));
        goto cleanup;
    }
    /* Can't specify a current larger than stored maximum; but
     * reducing maximum can silently reduce current.  */
    if (!(flags & VIR_DOMAIN_VCPU_MAXIMUM))
        max = entry->def->maxvcpus;
    if (vcpus > max) {
        xenXMError(VIR_ERR_INVALID_ARG,
                   _("requested vcpus is greater than max allowable"
                     " vcpus for the domain: %d > %d"), vcpus, max);
        goto cleanup;
    }

    if (flags & VIR_DOMAIN_VCPU_MAXIMUM) {
        entry->def->maxvcpus = vcpus;
        if (entry->def->vcpus > vcpus)
            entry->def->vcpus = vcpus;
    } else {
        entry->def->vcpus = vcpus;
    }

    /* If this fails, should we try to undo our changes to the
754 755
     * in-memory representation of the config file. I say not!
     */
756
    if (xenXMConfigSaveFile(domain->conn, entry->filename, entry->def) < 0)
D
Daniel P. Berrange 已提交
757 758
        goto cleanup;
    ret = 0;
759

D
Daniel P. Berrange 已提交
760 761 762
cleanup:
    xenUnifiedUnlock(priv);
    return ret;
763 764
}

765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
/**
 * xenXMDomainGetVcpusFlags:
 * @domain: pointer to domain object
 * @flags: bitwise-ORd from virDomainVcpuFlags
 *
 * Extract information about virtual CPUs of domain according to flags.
 *
 * Returns the number of vcpus on success, -1 if an error message was
 * issued, and -2 if the unified driver should keep trying.
 */
int
xenXMDomainGetVcpusFlags(virDomainPtr domain, unsigned int flags)
{
    xenUnifiedPrivatePtr priv;
    const char *filename;
    xenXMConfCachePtr entry;
    int ret = -2;

E
Eric Blake 已提交
783 784 785 786
    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
                  VIR_DOMAIN_VCPU_CONFIG |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
        return -1;
    }

    if (domain->id != -1)
        return -2;
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
        xenXMError(VIR_ERR_OPERATION_FAILED, "%s", _("domain not active"));
        return -1;
    }

    priv = domain->conn->privateData;
    xenUnifiedLock(priv);

    if (!(filename = virHashLookup(priv->nameConfigMap, domain->name)))
        goto cleanup;

    if (!(entry = virHashLookup(priv->configCache, filename)))
        goto cleanup;

    ret = ((flags & VIR_DOMAIN_VCPU_MAXIMUM) ? entry->def->maxvcpus
           : entry->def->vcpus);

cleanup:
    xenUnifiedUnlock(priv);
    return ret;
}

816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
/**
 * 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)
{
831
    xenUnifiedPrivatePtr priv;
832 833
    const char *filename;
    xenXMConfCachePtr entry;
834
    virBuffer mapbuf = VIR_BUFFER_INITIALIZER;
835
    char *mapstr = NULL, *mapsave = NULL;
836 837
    int i, j, n, comma = 0;
    int ret = -1;
838 839
    char *cpuset = NULL;
    int maxcpu = XEN_MAX_PHYSICAL_CPU;
840 841 842

    if (domain == NULL || domain->conn == NULL || domain->name == NULL
        || cpumap == NULL || maplen < 1 || maplen > (int)sizeof(cpumap_t)) {
843
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
844 845 846
        return -1;
    }
    if (domain->conn->flags & VIR_CONNECT_RO) {
847
        xenXMError(VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
848
                    "%s", _("read only connection"));
849 850 851
        return -1;
    }
    if (domain->id != -1) {
852
        xenXMError(VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
853
                    "%s", _("not inactive domain"));
854 855 856
        return -1;
    }

857
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
858
    xenUnifiedLock(priv);
859 860

    if (!(filename = virHashLookup(priv->nameConfigMap, domain->name))) {
861
        xenXMError(VIR_ERR_INTERNAL_ERROR, "%s", _("virHashLookup"));
D
Daniel P. Berrange 已提交
862
        goto cleanup;
863
    }
864
    if (!(entry = virHashLookup(priv->configCache, filename))) {
865
        xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
866
                    "%s", _("can't retrieve config file for domain"));
D
Daniel P. Berrange 已提交
867
        goto cleanup;
868 869 870 871 872 873 874 875
    }

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

876 877
                if (comma)
                    virBufferAddLit (&mapbuf, ",");
878 879
                comma = 1;

880
                virBufferAsprintf (&mapbuf, "%d", n);
881 882
            }

883
    if (virBufferError(&mapbuf)) {
884
        virBufferFreeAndReset(&mapbuf);
885
        virReportOOMError();
D
Daniel P. Berrange 已提交
886
        goto cleanup;
887 888 889
    }

    mapstr = virBufferContentAndReset(&mapbuf);
890
    mapsave = mapstr;
891

892
    if (VIR_ALLOC_N(cpuset, maxcpu) < 0) {
893
        virReportOOMError();
894 895
        goto cleanup;
    }
896
    if (virDomainCpuSetParse((const char **)&mapstr, 0,
897 898
                             cpuset, maxcpu) < 0)
        goto cleanup;
899

900 901 902 903
    VIR_FREE(entry->def->cpumask);
    entry->def->cpumask = cpuset;
    entry->def->cpumasklen = maxcpu;
    cpuset = NULL;
904

905
    if (xenXMConfigSaveFile(domain->conn, entry->filename, entry->def) < 0)
906 907 908 909 910
        goto cleanup;

    ret = 0;

 cleanup:
911
    VIR_FREE(mapsave);
912
    VIR_FREE(cpuset);
D
Daniel P. Berrange 已提交
913
    xenUnifiedUnlock(priv);
914 915 916
    return (ret);
}

917 918 919 920
/*
 * Find an inactive domain based on its name
 */
virDomainPtr xenXMDomainLookupByName(virConnectPtr conn, const char *domname) {
921
    xenUnifiedPrivatePtr priv;
922
    const char *filename;
923
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
924
    virDomainPtr ret = NULL;
925

926
    if (!VIR_IS_CONNECT(conn)) {
927
        xenXMError(VIR_ERR_INVALID_CONN, __FUNCTION__);
928 929 930
        return (NULL);
    }
    if (domname == NULL) {
931
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
932 933 934
        return (NULL);
    }

935
    priv = conn->privateData;
D
Daniel P. Berrange 已提交
936
    xenUnifiedLock(priv);
937

938
    if (!xenInotifyActive(conn) && xenXMConfigCacheRefresh (conn) < 0)
D
Daniel P. Berrange 已提交
939
        goto cleanup;
940

941
    if (!(filename = virHashLookup(priv->nameConfigMap, domname)))
D
Daniel P. Berrange 已提交
942
        goto cleanup;
943

D
Daniel P. Berrange 已提交
944 945
    if (!(entry = virHashLookup(priv->configCache, filename)))
        goto cleanup;
946

D
Daniel P. Berrange 已提交
947 948
    if (!(ret = virGetDomain(conn, domname, entry->def->uuid)))
        goto cleanup;
949 950 951

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

D
Daniel P. Berrange 已提交
954 955
cleanup:
    xenUnifiedUnlock(priv);
956 957 958 959 960 961 962
    return (ret);
}


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

967
    if (!memcmp(entry->def->uuid, wantuuid, VIR_UUID_BUFLEN))
968 969 970 971 972 973 974 975 976 977
        return (1);

    return (0);
}

/*
 * Find an inactive domain based on its UUID
 */
virDomainPtr xenXMDomainLookupByUUID(virConnectPtr conn,
                                     const unsigned char *uuid) {
978
    xenUnifiedPrivatePtr priv;
979
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
980
    virDomainPtr ret = NULL;
981 982

    if (!VIR_IS_CONNECT(conn)) {
983
        xenXMError(VIR_ERR_INVALID_CONN, __FUNCTION__);
984 985 986
        return (NULL);
    }
    if (uuid == NULL) {
987
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
988 989 990
        return (NULL);
    }

991
    priv = conn->privateData;
D
Daniel P. Berrange 已提交
992
    xenUnifiedLock(priv);
993

994
    if (!xenInotifyActive(conn) && xenXMConfigCacheRefresh (conn) < 0)
D
Daniel P. Berrange 已提交
995
        goto cleanup;
996

D
Daniel P. Berrange 已提交
997 998
    if (!(entry = virHashSearch(priv->configCache, xenXMDomainSearchForUUID, (const void *)uuid)))
        goto cleanup;
999

D
Daniel P. Berrange 已提交
1000 1001
    if (!(ret = virGetDomain(conn, entry->def->name, uuid)))
        goto cleanup;
1002

1003 1004
    /* Ensure its marked inactive, because may be cached
       handle to a previously active domain */
1005
    ret->id = -1;
1006

D
Daniel P. Berrange 已提交
1007 1008
cleanup:
    xenUnifiedUnlock(priv);
1009 1010 1011 1012 1013 1014 1015 1016 1017
    return (ret);
}


/*
 * Start a domain from an existing defined config file
 */
int xenXMDomainCreate(virDomainPtr domain) {
    char *sexpr;
D
Daniel P. Berrange 已提交
1018
    int ret = -1;
1019
    xenUnifiedPrivatePtr priv;
1020 1021 1022 1023
    const char *filename;
    xenXMConfCachePtr entry;

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

1025
    if (domain->id != -1)
1026 1027
        return (-1);

D
Daniel P. Berrange 已提交
1028 1029
    xenUnifiedLock(priv);

1030
    if (!(filename = virHashLookup(priv->nameConfigMap, domain->name)))
D
Daniel P. Berrange 已提交
1031
        goto error;
1032

1033
    if (!(entry = virHashLookup(priv->configCache, filename)))
D
Daniel P. Berrange 已提交
1034
        goto error;
1035

M
Markus Groß 已提交
1036
    if (!(sexpr = xenFormatSxpr(domain->conn, entry->def, priv->xendConfigVersion)))
D
Daniel P. Berrange 已提交
1037
        goto error;
1038

1039
    ret = xenDaemonDomainCreateXML(domain->conn, sexpr);
1040
    VIR_FREE(sexpr);
D
Daniel P. Berrange 已提交
1041 1042
    if (ret != 0)
        goto error;
1043

1044
    if ((ret = xenDaemonDomainLookupByName_ids(domain->conn, domain->name,
D
Daniel P. Berrange 已提交
1045 1046
                                               entry->def->uuid)) < 0)
        goto error;
1047
    domain->id = ret;
1048

1049
    if (xend_wait_for_devices(domain->conn, domain->name) < 0)
D
Daniel P. Berrange 已提交
1050
        goto error;
1051

1052
    if (xenDaemonDomainResume(domain) < 0)
D
Daniel P. Berrange 已提交
1053
        goto error;
1054

D
Daniel P. Berrange 已提交
1055
    xenUnifiedUnlock(priv);
1056 1057
    return (0);

D
Daniel P. Berrange 已提交
1058
 error:
1059
    if (domain->id != -1) {
1060
        xenDaemonDomainDestroyFlags(domain, 0);
1061
        domain->id = -1;
1062
    }
D
Daniel P. Berrange 已提交
1063
    xenUnifiedUnlock(priv);
1064
    return (-1);
1065 1066
}

1067 1068 1069 1070
/*
 * Create a config file for a domain, based on an XML
 * document describing its config
 */
1071 1072
virDomainPtr xenXMDomainDefineXML(virConnectPtr conn, const char *xml)
{
1073
    virDomainPtr ret;
1074 1075
    char *filename;
    const char *oldfilename;
1076
    virDomainDefPtr def = NULL;
1077
    xenXMConfCachePtr entry = NULL;
1078
    xenUnifiedPrivatePtr priv = (xenUnifiedPrivatePtr) conn->privateData;
1079 1080

    if (!VIR_IS_CONNECT(conn)) {
1081
        xenXMError(VIR_ERR_INVALID_CONN, __FUNCTION__);
1082 1083 1084
        return (NULL);
    }
    if (xml == NULL) {
1085
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
1086 1087 1088 1089 1090
        return (NULL);
    }
    if (conn->flags & VIR_CONNECT_RO)
        return (NULL);

D
Daniel P. Berrange 已提交
1091 1092
    xenUnifiedLock(priv);

1093
    if (!xenInotifyActive(conn) && xenXMConfigCacheRefresh (conn) < 0) {
D
Daniel P. Berrange 已提交
1094
        xenUnifiedUnlock(priv);
1095
        return (NULL);
D
Daniel P. Berrange 已提交
1096
    }
1097

1098
    if (!(def = virDomainDefParseString(priv->caps, xml,
M
Matthias Bolte 已提交
1099
                                        1 << VIR_DOMAIN_VIRT_XEN,
D
Daniel P. Berrange 已提交
1100
                                        VIR_DOMAIN_XML_INACTIVE))) {
1101
        xenUnifiedUnlock(priv);
1102
        return (NULL);
D
Daniel P. Berrange 已提交
1103
    }
1104

1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
    /*
     * check that if there is another domain defined with the same uuid
     * it has the same name
     */
    if ((entry = virHashSearch(priv->configCache, xenXMDomainSearchForUUID,
                               (const void *)&(def->uuid))) != NULL) {
        if ((entry->def != NULL) && (entry->def->name != NULL) &&
            (STRNEQ(def->name, entry->def->name))) {
            char uuidstr[VIR_UUID_STRING_BUFLEN];

            virUUIDFormat(entry->def->uuid, uuidstr);
1116
            xenXMError(VIR_ERR_OPERATION_FAILED,
1117 1118 1119 1120 1121 1122 1123 1124
                       _("domain '%s' is already defined with uuid %s"),
                       entry->def->name, uuidstr);
            entry = NULL;
            goto error;
        }
        entry = NULL;
    }

1125
    if (virHashLookup(priv->nameConfigMap, def->name)) {
1126 1127
        /* domain exists, we will overwrite it */

1128
        if (!(oldfilename = (char *)virHashLookup(priv->nameConfigMap, def->name))) {
1129
            xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1130
                       "%s", _("can't retrieve config filename for domain to overwrite"));
1131 1132 1133
            goto error;
        }

1134
        if (!(entry = virHashLookup(priv->configCache, oldfilename))) {
1135
            xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1136
                       "%s", _("can't retrieve config entry for domain to overwrite"));
1137 1138 1139 1140
            goto error;
        }

        /* Remove the name -> filename mapping */
1141
        if (virHashRemoveEntry(priv->nameConfigMap, def->name) < 0) {
1142
            xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1143
                       "%s", _("failed to remove old domain from config map"));
1144 1145 1146 1147
            goto error;
        }

        /* Remove the config record itself */
1148
        if (virHashRemoveEntry(priv->configCache, oldfilename) < 0) {
1149
            xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1150
                       "%s", _("failed to remove old domain from config map"));
1151 1152 1153 1154
            goto error;
        }

        entry = NULL;
1155
    }
1156

1157
    if (!(filename = virFileBuildPath(priv->configDir, def->name, NULL)))
1158 1159
        goto error;

1160
    if (xenXMConfigSaveFile(conn, filename, def) < 0)
1161 1162
        goto error;

1163
    if (VIR_ALLOC(entry) < 0) {
1164
        virReportOOMError();
1165
        goto error;
1166
    }
1167

1168
    if ((entry->refreshedAt = time(NULL)) == ((time_t)-1)) {
1169
        xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1170
                   "%s", _("unable to get current time"));
1171
        goto error;
1172
    }
1173

E
Eric Blake 已提交
1174 1175 1176 1177
    if ((entry->filename = strdup(filename)) == NULL) {
        virReportOOMError();
        goto error;
    }
1178
    entry->def = def;
1179

1180
    if (virHashAddEntry(priv->configCache, filename, entry) < 0) {
1181
        xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1182
                   "%s", _("unable to store config file handle"));
1183
        goto error;
1184
    }
1185

1186
    if (virHashAddEntry(priv->nameConfigMap, def->name, entry->filename) < 0) {
1187
        virHashSteal(priv->configCache, filename);
1188
        xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1189
                   "%s", _("unable to store config file handle"));
1190
        goto error;
1191 1192
    }

1193
    ret = virGetDomain(conn, def->name, def->uuid);
D
Daniel P. Berrange 已提交
1194
    xenUnifiedUnlock(priv);
1195
    VIR_FREE(filename);
1196 1197 1198
    return (ret);

 error:
1199
    VIR_FREE(filename);
E
Eric Blake 已提交
1200
    VIR_FREE(entry->filename);
1201
    VIR_FREE(entry);
1202
    virDomainDefFree(def);
D
Daniel P. Berrange 已提交
1203
    xenUnifiedUnlock(priv);
1204 1205 1206 1207 1208 1209 1210
    return (NULL);
}

/*
 * Delete a domain from disk
 */
int xenXMDomainUndefine(virDomainPtr domain) {
1211
    xenUnifiedPrivatePtr priv;
1212
    const char *filename;
1213
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
1214 1215
    int ret = -1;

1216
    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
1217
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
1218 1219 1220 1221 1222 1223
        return (-1);
    }

    if (domain->conn->flags & VIR_CONNECT_RO)
        return (-1);

1224
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
1225
    xenUnifiedLock(priv);
1226 1227

    if (!(filename = virHashLookup(priv->nameConfigMap, domain->name)))
D
Daniel P. Berrange 已提交
1228
        goto cleanup;
1229

1230
    if (!(entry = virHashLookup(priv->configCache, filename)))
D
Daniel P. Berrange 已提交
1231
        goto cleanup;
1232 1233

    if (unlink(entry->filename) < 0)
D
Daniel P. Berrange 已提交
1234
        goto cleanup;
1235

1236 1237 1238 1239 1240 1241
    if (virDomainObjIsActive(vm)) {
        vm->persistent = 0;
    } else {
        /* Remove the name -> filename mapping */
        if (virHashRemoveEntry(priv->nameConfigMap, domain->name) < 0)
            goto cleanup;
1242

1243 1244 1245 1246
        /* Remove the config record itself */
        if (virHashRemoveEntry(priv->configCache, entry->filename) < 0)
            goto cleanup;
    }
1247

D
Daniel P. Berrange 已提交
1248 1249 1250 1251 1252
    ret = 0;

cleanup:
    xenUnifiedUnlock(priv);
    return ret;
1253 1254 1255 1256
}

struct xenXMListIteratorContext {
    virConnectPtr conn;
1257
    int oom;
1258 1259
    int max;
    int count;
1260
    char ** names;
1261 1262
};

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

1267 1268 1269
    if (ctx->oom)
        return;

1270 1271 1272
    if (ctx->count == ctx->max)
        return;

1273
    dom = xenDaemonLookupByName(ctx->conn, name);
1274
    if (!dom) {
1275 1276 1277 1278
        if (!(ctx->names[ctx->count] = strdup(name)))
            ctx->oom = 1;
        else
            ctx->count++;
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
    } else {
        virDomainFree(dom);
    }
}


/*
 * List all defined domains, filtered to remove any which
 * are currently running
 */
1289
int xenXMListDefinedDomains(virConnectPtr conn, char **const names, int maxnames) {
1290
    xenUnifiedPrivatePtr priv;
1291
    struct xenXMListIteratorContext ctx;
1292
    int i, ret = -1;
1293 1294

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

1299
    priv = conn->privateData;
D
Daniel P. Berrange 已提交
1300
    xenUnifiedLock(priv);
1301

1302
    if (!xenInotifyActive(conn) && xenXMConfigCacheRefresh (conn) < 0)
D
Daniel P. Berrange 已提交
1303
        goto cleanup;
1304

1305 1306
    if (maxnames > virHashSize(priv->configCache))
        maxnames = virHashSize(priv->configCache);
1307 1308

    ctx.conn = conn;
1309
    ctx.oom = 0;
1310 1311 1312 1313
    ctx.count = 0;
    ctx.max = maxnames;
    ctx.names = names;

1314
    virHashForEach(priv->nameConfigMap, xenXMListIterator, &ctx);
1315 1316 1317 1318 1319

    if (ctx.oom) {
        for (i = 0; i < ctx.count; i++)
            VIR_FREE(ctx.names[i]);

1320
        virReportOOMError();
1321 1322 1323
        goto cleanup;
    }

D
Daniel P. Berrange 已提交
1324 1325 1326 1327 1328
    ret = ctx.count;

cleanup:
    xenUnifiedUnlock(priv);
    return ret;
1329 1330 1331 1332 1333 1334 1335
}

/*
 * Return the maximum number of defined domains - not filtered
 * based on number running
 */
int xenXMNumOfDefinedDomains(virConnectPtr conn) {
1336
    xenUnifiedPrivatePtr priv;
D
Daniel P. Berrange 已提交
1337
    int ret = -1;
1338

1339
    if (!VIR_IS_CONNECT(conn)) {
1340
        xenXMError(VIR_ERR_INVALID_CONN, __FUNCTION__);
1341 1342 1343
        return (-1);
    }

1344
    priv = conn->privateData;
D
Daniel P. Berrange 已提交
1345
    xenUnifiedLock(priv);
1346

1347
    if (!xenInotifyActive(conn) && xenXMConfigCacheRefresh (conn) < 0)
D
Daniel P. Berrange 已提交
1348
        goto cleanup;
1349

D
Daniel P. Berrange 已提交
1350 1351 1352 1353 1354
    ret = virHashSize(priv->nameConfigMap);

cleanup:
    xenUnifiedUnlock(priv);
    return ret;
1355 1356
}

1357

1358
/**
1359
 * xenXMDomainAttachDeviceFlags:
1360 1361
 * @domain: pointer to domain object
 * @xml: pointer to XML description of device
1362
 * @flags: an OR'ed set of virDomainDeviceModifyFlags
J
Jim Meyering 已提交
1363
 *
1364 1365
 * Create a virtual device attachment to backend.
 * XML description is translated into config file.
1366 1367
 * This driver only supports device allocation to
 * persisted config.
J
Jim Meyering 已提交
1368
 *
1369 1370 1371
 * Returns 0 in case of success, -1 in case of failure.
 */
static int
1372
xenXMDomainAttachDeviceFlags(virDomainPtr domain, const char *xml,
E
Eric Blake 已提交
1373 1374
                             unsigned int flags)
{
1375 1376
    const char *filename = NULL;
    xenXMConfCachePtr entry = NULL;
1377 1378
    int ret = -1;
    virDomainDeviceDefPtr dev = NULL;
1379
    virDomainDefPtr def;
1380
    xenUnifiedPrivatePtr priv;
1381

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

1384
    if ((!domain) || (!domain->conn) || (!domain->name) || (!xml)) {
1385
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
1386
        return -1;
1387
    }
1388

1389
    if (domain->conn->flags & VIR_CONNECT_RO)
1390
        return -1;
1391 1392

    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) ||
E
Eric Blake 已提交
1393
        (domain->id != -1 && flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)) {
1394 1395
        xenXMError(VIR_ERR_OPERATION_INVALID, "%s",
                   _("Xm driver only supports modifying persistent config"));
1396
        return -1;
1397
    }
1398

D
Daniel P. Berrange 已提交
1399 1400 1401
    priv = (xenUnifiedPrivatePtr) domain->conn->privateData;
    xenUnifiedLock(priv);

1402
    if (!(filename = virHashLookup(priv->nameConfigMap, domain->name)))
D
Daniel P. Berrange 已提交
1403
        goto cleanup;
1404
    if (!(entry = virHashLookup(priv->configCache, filename)))
D
Daniel P. Berrange 已提交
1405
        goto cleanup;
1406
    def = entry->def;
1407

1408
    if (!(dev = virDomainDeviceDefParse(priv->caps,
1409
                                        entry->def,
G
Guido Günther 已提交
1410
                                        xml, VIR_DOMAIN_XML_INACTIVE)))
D
Daniel P. Berrange 已提交
1411
        goto cleanup;
1412

1413 1414 1415
    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
    {
1416
        if (virDomainDiskInsert(def, dev->data.disk) < 0) {
1417
            virReportOOMError();
1418
            goto cleanup;
1419 1420
        }
        dev->data.disk = NULL;
1421
    }
1422
    break;
1423

1424 1425
    case VIR_DOMAIN_DEVICE_NET:
    {
1426
        if (VIR_REALLOC_N(def->nets, def->nnets+1) < 0) {
1427
            virReportOOMError();
1428 1429 1430
            goto cleanup;
        }
        def->nets[def->nnets++] = dev->data.net;
1431 1432
        dev->data.net = NULL;
        break;
1433 1434
    }

1435
    default:
1436 1437
        xenXMError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                   _("Xm driver only supports adding disk or network devices"));
1438 1439 1440 1441 1442 1443
        goto cleanup;
    }

    /* If this fails, should we try to undo our changes to the
     * in-memory representation of the config file. I say not!
     */
1444
    if (xenXMConfigSaveFile(domain->conn, entry->filename, entry->def) < 0)
1445 1446 1447 1448 1449
        goto cleanup;

    ret = 0;

 cleanup:
1450
    virDomainDeviceDefFree(dev);
D
Daniel P. Berrange 已提交
1451
    xenUnifiedUnlock(priv);
1452 1453 1454 1455 1456
    return ret;
}


/**
1457
 * xenXMDomainDetachDeviceFlags:
1458 1459
 * @domain: pointer to domain object
 * @xml: pointer to XML description of device
1460
 * @flags: an OR'ed set of virDomainDeviceModifyFlags
J
Jim Meyering 已提交
1461
 *
1462
 * Destroy a virtual device attachment to backend.
1463 1464
 * This driver only supports device deallocation from
 * persisted config.
1465 1466 1467 1468
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
static int
1469 1470
xenXMDomainDetachDeviceFlags(virDomainPtr domain, const char *xml,
                             unsigned int flags) {
1471 1472
    const char *filename = NULL;
    xenXMConfCachePtr entry = NULL;
1473
    virDomainDeviceDefPtr dev = NULL;
1474
    virDomainDefPtr def;
1475
    int ret = -1;
1476
    int i;
1477
    xenUnifiedPrivatePtr priv;
1478

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

1481
    if ((!domain) || (!domain->conn) || (!domain->name) || (!xml)) {
1482
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
1483
        return -1;
1484
    }
1485

1486
    if (domain->conn->flags & VIR_CONNECT_RO)
1487
        return -1;
1488 1489

    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) ||
E
Eric Blake 已提交
1490
        (domain->id != -1 && flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)) {
1491 1492
        xenXMError(VIR_ERR_OPERATION_INVALID, "%s",
                   _("Xm driver only supports modifying persistent config"));
1493
        return -1;
1494
    }
D
Daniel P. Berrange 已提交
1495 1496 1497 1498

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

1499
    if (!(filename = virHashLookup(priv->nameConfigMap, domain->name)))
D
Daniel P. Berrange 已提交
1500
        goto cleanup;
1501
    if (!(entry = virHashLookup(priv->configCache, filename)))
D
Daniel P. Berrange 已提交
1502
        goto cleanup;
1503
    def = entry->def;
1504

1505
    if (!(dev = virDomainDeviceDefParse(priv->caps,
1506
                                        entry->def,
G
Guido Günther 已提交
1507
                                        xml, VIR_DOMAIN_XML_INACTIVE)))
D
Daniel P. Berrange 已提交
1508
        goto cleanup;
1509

1510 1511 1512
    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
    {
1513 1514
        for (i = 0 ; i < def->ndisks ; i++) {
            if (def->disks[i]->dst &&
1515
                dev->data.disk->dst &&
1516 1517 1518 1519 1520
                STREQ(def->disks[i]->dst, dev->data.disk->dst)) {
                virDomainDiskDefFree(def->disks[i]);
                if (i < (def->ndisks - 1))
                    memmove(def->disks + i,
                            def->disks + i + 1,
1521 1522
                            sizeof(*def->disks) *
                            (def->ndisks - (i + 1)));
1523
                def->ndisks--;
1524
                break;
1525 1526
            }
        }
1527 1528 1529 1530 1531
        break;
    }

    case VIR_DOMAIN_DEVICE_NET:
    {
1532 1533 1534
        for (i = 0 ; i < def->nnets ; i++) {
            if (!memcmp(def->nets[i]->mac,
                        dev->data.net->mac,
1535
                        sizeof(def->nets[i]->mac))) {
1536 1537 1538 1539
                virDomainNetDefFree(def->nets[i]);
                if (i < (def->nnets - 1))
                    memmove(def->nets + i,
                            def->nets + i + 1,
1540 1541
                            sizeof(*def->nets) *
                            (def->nnets - (i + 1)));
1542
                def->nnets--;
1543 1544 1545 1546
                break;
            }
        }
        break;
1547
    }
1548
    default:
1549 1550 1551
        xenXMError(VIR_ERR_CONFIG_UNSUPPORTED,
                   _("device type '%s' cannot be detached"),
                   virDomainDeviceTypeToString(dev->type));
1552 1553 1554 1555 1556 1557
        goto cleanup;
    }

    /* If this fails, should we try to undo our changes to the
     * in-memory representation of the config file. I say not!
     */
1558
    if (xenXMConfigSaveFile(domain->conn, entry->filename, entry->def) < 0)
1559 1560 1561 1562 1563
        goto cleanup;

    ret = 0;

 cleanup:
1564
    virDomainDeviceDefFree(dev);
D
Daniel P. Berrange 已提交
1565
    xenUnifiedUnlock(priv);
1566 1567 1568
    return (ret);
}

R
Richard W.M. Jones 已提交
1569
int
1570
xenXMDomainBlockPeek (virDomainPtr dom ATTRIBUTE_UNUSED,
R
Richard W.M. Jones 已提交
1571 1572 1573 1574 1575
                      const char *path ATTRIBUTE_UNUSED,
                      unsigned long long offset ATTRIBUTE_UNUSED,
                      size_t size ATTRIBUTE_UNUSED,
                      void *buffer ATTRIBUTE_UNUSED)
{
1576
    xenXMError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
R
Richard W.M. Jones 已提交
1577 1578 1579
    return -1;
}

1580 1581 1582 1583

static char *xenXMAutostartLinkName(virDomainPtr dom)
{
    char *ret;
1584 1585
    if (virAsprintf(&ret, "/etc/xen/auto/%s", dom->name) < 0)
        return NULL;
1586 1587 1588 1589 1590 1591
    return ret;
}

static char *xenXMDomainConfigName(virDomainPtr dom)
{
    char *ret;
1592 1593
    if (virAsprintf(&ret, "/etc/xen/%s", dom->name) < 0)
        return NULL;
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
    return ret;
}

int xenXMDomainGetAutostart(virDomainPtr dom, int *autostart)
{
    char *linkname = xenXMAutostartLinkName(dom);
    char *config = xenXMDomainConfigName(dom);
    int ret = -1;

    if (!linkname || !config) {
1604
        virReportOOMError();
1605 1606 1607 1608 1609
        goto cleanup;
    }

    *autostart = virFileLinkPointsTo(linkname, config);
    if (*autostart < 0) {
1610
        virReportSystemError(errno,
1611 1612
                             _("cannot check link %s points to config %s"),
                             linkname, config);
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
        goto cleanup;
    }

    ret = 0;

cleanup:
    VIR_FREE(linkname);
    VIR_FREE(config);
    return ret;
}


int xenXMDomainSetAutostart(virDomainPtr dom, int autostart)
{
    char *linkname = xenXMAutostartLinkName(dom);
    char *config = xenXMDomainConfigName(dom);
    int ret = -1;

    if (!linkname || !config) {
1632
        virReportOOMError();
1633 1634 1635 1636 1637 1638
        goto cleanup;
    }

    if (autostart) {
        if (symlink(config, linkname) < 0 &&
            errno != EEXIST) {
1639
            virReportSystemError(errno,
1640 1641
                                 _("failed to create link %s to %s"),
                                 config, linkname);
1642 1643 1644 1645 1646
            goto cleanup;
        }
    } else {
        if (unlink(linkname)  < 0 &&
            errno != ENOENT) {
1647
            virReportSystemError(errno,
1648 1649
                                 _("failed to remove link %s"),
                                 linkname);
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
            goto cleanup;
        }
    }
    ret = 0;

cleanup:
    VIR_FREE(linkname);
    VIR_FREE(config);

    return ret;
}