xm_internal.c 45.6 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
    char *filename = NULL;
1074
    const char *oldfilename;
1075
    virDomainDefPtr def = NULL;
1076
    virConfPtr conf = 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
    if (!(conf = xenFormatXM(conn, def, priv->xendConfigVersion)))
        goto error;

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

1128
    if (virHashLookup(priv->nameConfigMap, def->name)) {
1129 1130
        /* domain exists, we will overwrite it */

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

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

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

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

        entry = NULL;
1158
    }
1159

1160
    if (!(filename = virFileBuildPath(priv->configDir, def->name, NULL)))
1161 1162
        goto error;

1163
    if (virConfWriteFile(filename, conf) < 0)
1164 1165
        goto error;

1166
    if (VIR_ALLOC(entry) < 0) {
1167
        virReportOOMError();
1168
        goto error;
1169
    }
1170

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

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

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

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

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

 error:
1202
    VIR_FREE(filename);
1203 1204
    if (entry)
        VIR_FREE(entry->filename);
1205
    VIR_FREE(entry);
1206
    virConfFree(conf);
1207
    virDomainDefFree(def);
D
Daniel P. Berrange 已提交
1208
    xenUnifiedUnlock(priv);
1209 1210 1211 1212 1213 1214 1215
    return (NULL);
}

/*
 * Delete a domain from disk
 */
int xenXMDomainUndefine(virDomainPtr domain) {
1216
    xenUnifiedPrivatePtr priv;
1217
    const char *filename;
1218
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
1219 1220
    int ret = -1;

1221
    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
1222
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
1223 1224 1225
        return (-1);
    }

1226 1227
    if (domain->id != -1)
        return (-1);
1228 1229 1230
    if (domain->conn->flags & VIR_CONNECT_RO)
        return (-1);

1231
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
1232
    xenUnifiedLock(priv);
1233 1234

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

1237
    if (!(entry = virHashLookup(priv->configCache, filename)))
D
Daniel P. Berrange 已提交
1238
        goto cleanup;
1239 1240

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

1243 1244 1245
    /* Remove the name -> filename mapping */
    if (virHashRemoveEntry(priv->nameConfigMap, domain->name) < 0)
        goto cleanup;
1246

1247 1248 1249
    /* Remove the config record itself */
    if (virHashRemoveEntry(priv->configCache, entry->filename) < 0)
        goto cleanup;
1250

D
Daniel P. Berrange 已提交
1251 1252 1253 1254 1255
    ret = 0;

cleanup:
    xenUnifiedUnlock(priv);
    return ret;
1256 1257 1258 1259
}

struct xenXMListIteratorContext {
    virConnectPtr conn;
1260
    int oom;
1261 1262
    int max;
    int count;
1263
    char ** names;
1264 1265
};

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

1270 1271 1272
    if (ctx->oom)
        return;

1273 1274 1275
    if (ctx->count == ctx->max)
        return;

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


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

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

1302
    priv = conn->privateData;
D
Daniel P. Berrange 已提交
1303
    xenUnifiedLock(priv);
1304

1305
    if (!xenInotifyActive(conn) && xenXMConfigCacheRefresh (conn) < 0)
D
Daniel P. Berrange 已提交
1306
        goto cleanup;
1307

1308 1309
    if (maxnames > virHashSize(priv->configCache))
        maxnames = virHashSize(priv->configCache);
1310 1311

    ctx.conn = conn;
1312
    ctx.oom = 0;
1313 1314 1315 1316
    ctx.count = 0;
    ctx.max = maxnames;
    ctx.names = names;

1317
    virHashForEach(priv->nameConfigMap, xenXMListIterator, &ctx);
1318 1319 1320 1321 1322

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

1323
        virReportOOMError();
1324 1325 1326
        goto cleanup;
    }

D
Daniel P. Berrange 已提交
1327 1328 1329 1330 1331
    ret = ctx.count;

cleanup:
    xenUnifiedUnlock(priv);
    return ret;
1332 1333 1334 1335 1336 1337 1338
}

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

1342
    if (!VIR_IS_CONNECT(conn)) {
1343
        xenXMError(VIR_ERR_INVALID_CONN, __FUNCTION__);
1344 1345 1346
        return (-1);
    }

1347
    priv = conn->privateData;
D
Daniel P. Berrange 已提交
1348
    xenUnifiedLock(priv);
1349

1350
    if (!xenInotifyActive(conn) && xenXMConfigCacheRefresh (conn) < 0)
D
Daniel P. Berrange 已提交
1351
        goto cleanup;
1352

D
Daniel P. Berrange 已提交
1353 1354 1355 1356 1357
    ret = virHashSize(priv->nameConfigMap);

cleanup:
    xenUnifiedUnlock(priv);
    return ret;
1358 1359
}

1360

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

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

1387
    if ((!domain) || (!domain->conn) || (!domain->name) || (!xml)) {
1388
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
1389
        return -1;
1390
    }
1391

1392
    if (domain->conn->flags & VIR_CONNECT_RO)
1393
        return -1;
1394 1395

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

D
Daniel P. Berrange 已提交
1402 1403 1404
    priv = (xenUnifiedPrivatePtr) domain->conn->privateData;
    xenUnifiedLock(priv);

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

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

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

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

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

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

    ret = 0;

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


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

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

1484
    if ((!domain) || (!domain->conn) || (!domain->name) || (!xml)) {
1485
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
1486
        return -1;
1487
    }
1488

1489
    if (domain->conn->flags & VIR_CONNECT_RO)
1490
        return -1;
1491 1492

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

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

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

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

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

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

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

    ret = 0;

 cleanup:
1567
    virDomainDeviceDefFree(dev);
D
Daniel P. Berrange 已提交
1568
    xenUnifiedUnlock(priv);
1569 1570 1571
    return (ret);
}

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

1584 1585 1586 1587

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

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

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

    if (!linkname || !config) {
1608
        virReportOOMError();
1609 1610 1611 1612 1613
        goto cleanup;
    }

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

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

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

    return ret;
}