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 "virhash.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
    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",
E
Eric Blake 已提交
731
                   _("could not determine max vcpus for the domain"));
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
        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(mapstr, 0, cpuset, maxcpu) < 0)
897
        goto cleanup;
898

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

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

    ret = 0;

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

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

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

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

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

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

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

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

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

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


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

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

    return (0);
}

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
    /*
     * 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);
1115
            xenXMError(VIR_ERR_OPERATION_FAILED,
1116 1117 1118 1119 1120 1121 1122 1123
                       _("domain '%s' is already defined with uuid %s"),
                       entry->def->name, uuidstr);
            entry = NULL;
            goto error;
        }
        entry = NULL;
    }

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

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

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

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

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

        entry = NULL;
1154
    }
1155

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

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

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

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

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

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

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

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

 error:
1198
    VIR_FREE(filename);
1199 1200
    if (entry)
        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
        return (-1);
    }

1221 1222
    if (domain->id != -1)
        return (-1);
1223 1224 1225
    if (domain->conn->flags & VIR_CONNECT_RO)
        return (-1);

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

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

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

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

1238 1239 1240
    /* Remove the name -> filename mapping */
    if (virHashRemoveEntry(priv->nameConfigMap, domain->name) < 0)
        goto cleanup;
1241

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

D
Daniel P. Berrange 已提交
1246 1247 1248 1249 1250
    ret = 0;

cleanup:
    xenUnifiedUnlock(priv);
    return ret;
1251 1252 1253 1254
}

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

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

1265 1266 1267
    if (ctx->oom)
        return;

1268 1269 1270
    if (ctx->count == ctx->max)
        return;

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


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

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

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

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

1303 1304
    if (maxnames > virHashSize(priv->configCache))
        maxnames = virHashSize(priv->configCache);
1305 1306

    ctx.conn = conn;
1307
    ctx.oom = 0;
1308 1309 1310 1311
    ctx.count = 0;
    ctx.max = maxnames;
    ctx.names = names;

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

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

1318
        virReportOOMError();
1319 1320 1321
        goto cleanup;
    }

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

cleanup:
    xenUnifiedUnlock(priv);
    return ret;
1327 1328 1329 1330 1331 1332 1333
}

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

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

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

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

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

cleanup:
    xenUnifiedUnlock(priv);
    return ret;
1353 1354
}

1355

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

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

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

1387
    if (domain->conn->flags & VIR_CONNECT_RO)
1388
        return -1;
1389 1390

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

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

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

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

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

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

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

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

    ret = 0;

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


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

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

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

1484
    if (domain->conn->flags & VIR_CONNECT_RO)
1485
        return -1;
1486 1487

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

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

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

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

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

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

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

    ret = 0;

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

R
Richard W.M. Jones 已提交
1567
int
1568
xenXMDomainBlockPeek (virDomainPtr dom ATTRIBUTE_UNUSED,
R
Richard W.M. Jones 已提交
1569 1570 1571 1572 1573
                      const char *path ATTRIBUTE_UNUSED,
                      unsigned long long offset ATTRIBUTE_UNUSED,
                      size_t size ATTRIBUTE_UNUSED,
                      void *buffer ATTRIBUTE_UNUSED)
{
1574 1575
    xenXMError(VIR_ERR_OPERATION_INVALID, "%s",
               _("block peeking not implemented"));
R
Richard W.M. Jones 已提交
1576 1577 1578
    return -1;
}

1579 1580 1581 1582

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

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

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

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

    *autostart = virFileLinkPointsTo(linkname, config);
    if (*autostart < 0) {
1609
        virReportSystemError(errno,
1610 1611
                             _("cannot check link %s points to config %s"),
                             linkname, config);
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
        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) {
1631
        virReportOOMError();
1632 1633 1634 1635 1636 1637
        goto cleanup;
    }

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

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

    return ret;
}