xm_internal.c 45.7 KB
Newer Older
1 2 3
/*
 * xm_internal.h: helper routines for dealing with inactive domains
 *
4
 * Copyright (C) 2006-2007, 2009-2011 Red Hat, Inc.
5
 * Copyright (C) 2006 Daniel P. Berrange
6
 *
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
22 23 24
 *
 */

25
#include <config.h>
26

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

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

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

53
#define VIR_FROM_THIS VIR_FROM_XENXM
54

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

63 64 65 66 67
/* The true Xen limit varies but so far is always way
   less than 1024, which is the Linux kernel limit according
   to sched.h, so we'll match that for now */
#define XEN_MAX_PHYSICAL_CPU 1024

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

74 75 76 77 78 79 80
#define XM_REFRESH_INTERVAL 10

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

83
struct xenUnifiedDriver xenXMDriver = {
84 85 86
    xenXMOpen, /* open */
    xenXMClose, /* close */
    NULL, /* version */
87
    NULL, /* hostname */
88
    NULL, /* nodeGetInfo */
89
    NULL, /* getCapabilities */
90 91
    NULL, /* listDomains */
    NULL, /* numOfDomains */
92
    NULL, /* domainCreateXML */
93 94 95 96 97 98 99 100 101 102 103 104
    NULL, /* domainSuspend */
    NULL, /* domainResume */
    NULL, /* domainShutdown */
    NULL, /* domainReboot */
    NULL, /* domainDestroy */
    NULL, /* domainGetOSType */
    xenXMDomainGetMaxMemory, /* domainGetMaxMemory */
    xenXMDomainSetMaxMemory, /* domainSetMaxMemory */
    xenXMDomainSetMemory, /* domainMaxMemory */
    xenXMDomainGetInfo, /* domainGetInfo */
    NULL, /* domainSave */
    NULL, /* domainRestore */
D
Daniel Veillard 已提交
105
    NULL, /* domainCoreDump */
106
    NULL, /* domainScreenshot */
107
    xenXMDomainPinVcpu, /* domainPinVcpu */
108 109 110 111 112 113
    NULL, /* domainGetVcpus */
    xenXMListDefinedDomains, /* listDefinedDomains */
    xenXMNumOfDefinedDomains, /* numOfDefinedDomains */
    xenXMDomainCreate, /* domainCreate */
    xenXMDomainDefineXML, /* domainDefineXML */
    xenXMDomainUndefine, /* domainUndefine */
114 115
    xenXMDomainAttachDeviceFlags, /* domainAttachDeviceFlags */
    xenXMDomainDetachDeviceFlags, /* domainDetachDeviceFlags */
116
    NULL, /* domainUpdateDeviceFlags */
117 118
    NULL, /* domainGetAutostart */
    NULL, /* domainSetAutostart */
119 120 121
    NULL, /* domainGetSchedulerType */
    NULL, /* domainGetSchedulerParameters */
    NULL, /* domainSetSchedulerParameters */
122 123
};

124
#define xenXMError(code, ...)                                              \
125
        virReportErrorHelper(VIR_FROM_XENXM, code, __FILE__,               \
126
                             __FUNCTION__, __LINE__, __VA_ARGS__)
127

128
#ifndef WITH_XEN_INOTIFY
129 130 131 132
static int xenInotifyActive(virConnectPtr conn ATTRIBUTE_UNUSED)
{
   return 0;
}
133
#else
134 135 136 137
static int xenInotifyActive(virConnectPtr conn)
{
   xenUnifiedPrivatePtr priv = (xenUnifiedPrivatePtr) conn->privateData;
   return priv->inotifyWatch > 0;
138
}
139
#endif
140

141 142

/* Release memory associated with a cached config object */
143
static void xenXMConfigFree(void *payload, const void *key ATTRIBUTE_UNUSED) {
144
    xenXMConfCachePtr entry = (xenXMConfCachePtr)payload;
145
    virDomainDefFree(entry->def);
E
Eric Blake 已提交
146
    VIR_FREE(entry->filename);
147
    VIR_FREE(entry);
148 149
}

150 151 152 153
struct xenXMConfigReaperData {
    xenUnifiedPrivatePtr priv;
    time_t now;
};
154

155
/* Remove any configs which were not refreshed recently */
156
static int xenXMConfigReaper(const void *payload, const void *key ATTRIBUTE_UNUSED, const void *data) {
157
    const struct xenXMConfigReaperData *args = data;
158 159
    xenXMConfCachePtr entry = (xenXMConfCachePtr)payload;

160 161
    /* We're going to purge this config file, so check if it
       is currently mapped as owner of a named domain. */
162
    if (entry->refreshedAt != args->now) {
163
        const char *olddomname = entry->def->name;
164
        char *nameowner = (char *)virHashLookup(args->priv->nameConfigMap, olddomname);
165
        if (nameowner && STREQ(nameowner, key)) {
166
            virHashRemoveEntry(args->priv->nameConfigMap, olddomname);
167 168 169 170 171 172
        }
        return (1);
    }
    return (0);
}

173 174 175 176 177

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

180
    if (!(conf = virConfReadFile(filename, 0)))
181 182
        return NULL;

M
Markus Groß 已提交
183
    def = xenParseXM(conf, priv->xendConfigVersion, priv->caps);
184 185 186 187 188 189 190 191
    virConfFree(conf);

    return def;
}

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

M
Markus Groß 已提交
195
    if (!(conf = xenFormatXM(conn, def, priv->xendConfigVersion)))
196 197 198 199 200 201 202
        return -1;

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

D
Daniel P. Berrange 已提交
203 204 205 206 207

/*
 * Caller must hold the lock on 'conn->privateData' before
 * calling this funtion
 */
208
int
209
xenXMConfigCacheRemoveFile(virConnectPtr conn,
210 211
                           const char *filename)
{
212
    xenUnifiedPrivatePtr priv = conn->privateData;
213 214
    xenXMConfCachePtr entry;

215
    entry = virHashLookup(priv->configCache, filename);
216
    if (!entry) {
217
        VIR_DEBUG("No config entry for %s", filename);
218 219 220
        return 0;
    }

221 222
    virHashRemoveEntry(priv->nameConfigMap, entry->def->name);
    virHashRemoveEntry(priv->configCache, filename);
223
    VIR_DEBUG("Removed %s %s", entry->def->name, filename);
224 225 226 227
    return 0;
}


D
Daniel P. Berrange 已提交
228 229 230 231
/*
 * Caller must hold the lock on 'conn->privateData' before
 * calling this funtion
 */
232 233 234
int
xenXMConfigCacheAddFile(virConnectPtr conn, const char *filename)
{
235
    xenUnifiedPrivatePtr priv = conn->privateData;
236 237 238 239 240
    xenXMConfCachePtr entry;
    struct stat st;
    int newborn = 0;
    time_t now = time(NULL);

241
    VIR_DEBUG("Adding file %s", filename);
242 243 244

    /* Get modified time */
    if ((stat(filename, &st) < 0)) {
245
        virReportSystemError(errno,
246 247
                             _("cannot stat: %s"),
                             filename);
248 249 250 251 252 253
        return -1;
    }

    /* Ignore zero length files, because inotify fires before
       any content has actually been created */
    if (st.st_size == 0) {
254
        VIR_DEBUG("Ignoring zero length file %s", filename);
255 256 257 258 259
        return -1;
    }

    /* If we already have a matching entry and it is not
    modified, then carry on to next one*/
260
    if ((entry = virHashLookup(priv->configCache, filename))) {
261 262 263 264 265 266 267 268 269 270
        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 */
271
        nameowner = (char *)virHashLookup(priv->nameConfigMap, entry->def->name);
272
        if (nameowner && STREQ(nameowner, filename)) {
273
            virHashRemoveEntry(priv->nameConfigMap, entry->def->name);
274 275 276 277 278 279 280 281
        }

        /* Clear existing config entry which needs refresh */
        virDomainDefFree(entry->def);
        entry->def = NULL;
    } else { /* Completely new entry */
        newborn = 1;
        if (VIR_ALLOC(entry) < 0) {
282
            virReportOOMError();
283 284
            return -1;
        }
E
Eric Blake 已提交
285 286 287 288 289
        if ((entry->filename = strdup(filename)) == NULL) {
            virReportOOMError();
            VIR_FREE(entry);
            return -1;
        }
290 291 292 293
    }
    entry->refreshedAt = now;

    if (!(entry->def = xenXMConfigReadFile(conn, entry->filename))) {
294
        VIR_DEBUG("Failed to read %s", entry->filename);
295
        if (!newborn)
296
            virHashSteal(priv->configCache, filename);
E
Eric Blake 已提交
297
        VIR_FREE(entry->filename);
298 299 300 301 302 303 304
        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) {
305
        if (virHashAddEntry(priv->configCache, entry->filename, entry) < 0) {
306
            virDomainDefFree(entry->def);
E
Eric Blake 已提交
307
            VIR_FREE(entry->filename);
308
            VIR_FREE(entry);
309
            xenXMError(VIR_ERR_INTERNAL_ERROR,
310 311 312 313 314 315 316 317
                        "%s", _("xenXMConfigCacheRefresh: virHashAddEntry"));
            return -1;
        }
    }

    /* See if we need to map this config file in as the primary owner
        * of the domain in question
        */
318
    if (!virHashLookup(priv->nameConfigMap, entry->def->name)) {
E
Eric Blake 已提交
319 320
        if (virHashAddEntry(priv->nameConfigMap, entry->def->name,
                            entry->filename) < 0) {
321
            virHashSteal(priv->configCache, filename);
322
            virDomainDefFree(entry->def);
E
Eric Blake 已提交
323
            VIR_FREE(entry->filename);
324 325 326
            VIR_FREE(entry);
        }
    }
327
    VIR_DEBUG("Added config %s %s", entry->def->name, filename);
328 329 330

    return 0;
}
331

332
/* This method is called by various methods to scan /etc/xen
D
Daniel P. Berrange 已提交
333 334 335 336 337 338 339 340
 * (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
 */
341
int xenXMConfigCacheRefresh (virConnectPtr conn) {
342
    xenUnifiedPrivatePtr priv = conn->privateData;
343 344 345 346
    DIR *dh;
    struct dirent *ent;
    time_t now = time(NULL);
    int ret = -1;
347
    struct xenXMConfigReaperData args;
348 349

    if (now == ((time_t)-1)) {
350
        virReportSystemError(errno,
351
                             "%s", _("cannot get time of day"));
352 353 354 355
        return (-1);
    }

    /* Rate limit re-scans */
356
    if ((now - priv->lastRefresh) < XM_REFRESH_INTERVAL)
357 358
        return (0);

359
    priv->lastRefresh = now;
360 361

    /* Process the files in the config dir */
362
    if (!(dh = opendir(priv->configDir))) {
363
        virReportSystemError(errno,
364
                             _("cannot read directory %s"),
365
                             priv->configDir);
366 367 368 369 370
        return (-1);
    }

    while ((ent = readdir(dh))) {
        struct stat st;
371
        char *path;
372 373 374 375 376 377

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

        /* Like 'dot' files... */
378
        if (STRPREFIX(ent->d_name, "."))
379 380
            continue;
        /* ...and the XenD server config file */
381
        if (STRPREFIX(ent->d_name, XEND_CONFIG_FILE))
382 383
            continue;
        /* ...and random PCI config cruft */
384
        if (STRPREFIX(ent->d_name, XEND_PCI_CONFIG_PREFIX))
385 386
            continue;
        /* ...and the example domain configs */
387
        if (STRPREFIX(ent->d_name, XM_EXAMPLE_PREFIX))
388 389
            continue;
        /* ...and the QEMU networking script */
390
        if (STRPREFIX(ent->d_name, QEMU_IF_SCRIPT))
391 392 393 394 395 396 397 398 399
            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 */
400 401 402 403
        if (!(path = virFileBuildPath(priv->configDir, ent->d_name, NULL))) {
            closedir(dh);
            return -1;
        }
404 405 406 407

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

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

        VIR_FREE(path);
419 420 421 422 423 424
    }

    /* 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 */
425 426
    args.now = now;
    args.priv = priv;
427
    virHashRemoveSet(priv->configCache, xenXMConfigReaper, &args);
428 429
    ret = 0;

430
    closedir(dh);
431 432 433 434 435 436

    return (ret);
}


/*
437 438 439 440
 * 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
441
 */
442
virDrvOpenStatus
443
xenXMOpen (virConnectPtr conn,
444
           virConnectAuthPtr auth ATTRIBUTE_UNUSED,
445
           unsigned int flags ATTRIBUTE_UNUSED)
446
{
447 448 449 450
    xenUnifiedPrivatePtr priv = conn->privateData;

    priv->configDir = XM_CONFIG_DIR;

451
    priv->configCache = virHashCreate(50, xenXMConfigFree);
452 453
    if (!priv->configCache)
        return (-1);
454
    priv->nameConfigMap = virHashCreate(50, NULL);
455
    if (!priv->nameConfigMap) {
456
        virHashFree(priv->configCache);
457 458
        priv->configCache = NULL;
        return (-1);
459
    }
460 461 462 463
    /* Force the cache to be reloaded next time that
     * xenXMConfigCacheRefresh is called.
     */
    priv->lastRefresh = 0;
464 465 466 467 468

    return (0);
}

/*
469 470
 * Free the cached config files associated with this
 * connection
471
 */
472 473 474
int xenXMClose(virConnectPtr conn) {
    xenUnifiedPrivatePtr priv = conn->privateData;

475 476
    virHashFree(priv->nameConfigMap);
    virHashFree(priv->configCache);
477

478 479 480
    return (0);
}

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
/*
 * Since these are all offline domains, the state is always SHUTOFF.
 */
int
xenXMDomainGetState(virDomainPtr domain,
                    int *state,
                    int *reason,
                    unsigned int flags ATTRIBUTE_UNUSED)
{
    if (domain->id != -1)
        return -1;

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

    return 0;
}


501 502
/*
 * Since these are all offline domains, we only return info about
503
 * VCPUs and memory.
504 505
 */
int xenXMDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info) {
506
    xenUnifiedPrivatePtr priv;
507
    const char *filename;
508 509
    xenXMConfCachePtr entry;
    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
510
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
511 512 513
        return(-1);
    }

514
    if (domain->id != -1)
515 516
        return (-1);

517
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
518
    xenUnifiedLock(priv);
519 520

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

523
    if (!(entry = virHashLookup(priv->configCache, filename)))
D
Daniel P. Berrange 已提交
524
        goto error;
525 526

    memset(info, 0, sizeof(virDomainInfo));
527 528
    info->maxMem = entry->def->mem.max_balloon;
    info->memory = entry->def->mem.cur_balloon;
529
    info->nrVirtCpu = entry->def->vcpus;
530 531 532
    info->state = VIR_DOMAIN_SHUTOFF;
    info->cpuTime = 0;

D
Daniel P. Berrange 已提交
533
    xenUnifiedUnlock(priv);
534 535
    return (0);

D
Daniel P. Berrange 已提交
536 537 538
error:
    xenUnifiedUnlock(priv);
    return -1;
539 540 541
}


542 543
/*
 * Turn a config record into a lump of XML describing the
544
 * domain, suitable for later feeding for virDomainCreateXML
545
 */
546
char *xenXMDomainGetXMLDesc(virDomainPtr domain, int flags) {
547
    xenUnifiedPrivatePtr priv;
548 549
    const char *filename;
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
550
    char *ret = NULL;
551 552

    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
553
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
554 555
        return(NULL);
    }
556
    if (domain->id != -1)
557 558
        return (NULL);

559
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
560
    xenUnifiedLock(priv);
561 562

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

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

568
    ret = virDomainDefFormat(entry->def, flags);
569

D
Daniel P. Berrange 已提交
570 571 572
cleanup:
    xenUnifiedUnlock(priv);
    return ret;
573 574 575
}


576 577 578 579
/*
 * Update amount of memory in the config file
 */
int xenXMDomainSetMemory(virDomainPtr domain, unsigned long memory) {
580
    xenUnifiedPrivatePtr priv;
581
    const char *filename;
582
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
583
    int ret = -1;
584 585

    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
586
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
587 588 589 590
        return (-1);
    }
    if (domain->conn->flags & VIR_CONNECT_RO)
        return (-1);
591
    if (domain->id != -1)
592
        return (-1);
593 594
    if (memory < 1024 * MIN_XEN_GUEST_SIZE)
        return (-1);
595

596
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
597
    xenUnifiedLock(priv);
598 599

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

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

605 606 607
    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;
608 609 610 611

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

D
Daniel P. Berrange 已提交
616 617 618
cleanup:
    xenUnifiedUnlock(priv);
    return ret;
619 620 621 622 623 624
}

/*
 * Update maximum memory limit in config
 */
int xenXMDomainSetMaxMemory(virDomainPtr domain, unsigned long memory) {
625
    xenUnifiedPrivatePtr priv;
626
    const char *filename;
627
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
628
    int ret = -1;
629 630

    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
631
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
632 633 634 635
        return (-1);
    }
    if (domain->conn->flags & VIR_CONNECT_RO)
        return (-1);
636
    if (domain->id != -1)
637 638
        return (-1);

639
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
640
    xenUnifiedLock(priv);
641 642

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

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

648 649 650
    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;
651 652 653 654

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

D
Daniel P. Berrange 已提交
659 660 661
cleanup:
    xenUnifiedUnlock(priv);
    return ret;
662 663 664 665 666 667
}

/*
 * Get max memory limit from config
 */
unsigned long xenXMDomainGetMaxMemory(virDomainPtr domain) {
668
    xenUnifiedPrivatePtr priv;
669
    const char *filename;
670
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
671
    unsigned long ret = 0;
672 673

    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
674
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
D
Daniel P. Berrange 已提交
675
        return (0);
676
    }
677
    if (domain->id != -1)
D
Daniel P. Berrange 已提交
678
        return (0);
679

680
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
681
    xenUnifiedLock(priv);
682 683

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

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

689
    ret = entry->def->mem.max_balloon;
690

D
Daniel P. Berrange 已提交
691 692 693
cleanup:
    xenUnifiedUnlock(priv);
    return ret;
694 695
}

696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
/*
 * 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;

    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
        return -1;
    }
    if (domain->conn->flags & VIR_CONNECT_RO) {
        xenXMError(VIR_ERR_OPERATION_DENIED, __FUNCTION__);
        return -1;
    }
    if (domain->id != -1)
        return -2;
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
        xenXMError(VIR_ERR_OPERATION_INVALID, "%s",
                   _("domain is not running"));
        return -1;
    }

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

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

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

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

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

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

D
Daniel P. Berrange 已提交
774 775 776
cleanup:
    xenUnifiedUnlock(priv);
    return ret;
777 778
}

779 780 781 782 783 784 785 786 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 816 817 818 819 820 821 822 823 824 825
/**
 * 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;

    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;
}

826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
/**
 * 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)
{
841
    xenUnifiedPrivatePtr priv;
842 843
    const char *filename;
    xenXMConfCachePtr entry;
844
    virBuffer mapbuf = VIR_BUFFER_INITIALIZER;
845
    char *mapstr = NULL, *mapsave = NULL;
846 847
    int i, j, n, comma = 0;
    int ret = -1;
848 849
    char *cpuset = NULL;
    int maxcpu = XEN_MAX_PHYSICAL_CPU;
850 851 852

    if (domain == NULL || domain->conn == NULL || domain->name == NULL
        || cpumap == NULL || maplen < 1 || maplen > (int)sizeof(cpumap_t)) {
853
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
854 855 856
        return -1;
    }
    if (domain->conn->flags & VIR_CONNECT_RO) {
857
        xenXMError(VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
858
                    "%s", _("read only connection"));
859 860 861
        return -1;
    }
    if (domain->id != -1) {
862
        xenXMError(VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
863
                    "%s", _("not inactive domain"));
864 865 866
        return -1;
    }

867
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
868
    xenUnifiedLock(priv);
869 870

    if (!(filename = virHashLookup(priv->nameConfigMap, domain->name))) {
871
        xenXMError(VIR_ERR_INTERNAL_ERROR, "%s", _("virHashLookup"));
D
Daniel P. Berrange 已提交
872
        goto cleanup;
873
    }
874
    if (!(entry = virHashLookup(priv->configCache, filename))) {
875
        xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
876
                    "%s", _("can't retrieve config file for domain"));
D
Daniel P. Berrange 已提交
877
        goto cleanup;
878 879 880 881 882 883 884 885
    }

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

886 887
                if (comma)
                    virBufferAddLit (&mapbuf, ",");
888 889
                comma = 1;

890
                virBufferAsprintf (&mapbuf, "%d", n);
891 892
            }

893
    if (virBufferError(&mapbuf)) {
894
        virBufferFreeAndReset(&mapbuf);
895
        virReportOOMError();
D
Daniel P. Berrange 已提交
896
        goto cleanup;
897 898 899
    }

    mapstr = virBufferContentAndReset(&mapbuf);
900
    mapsave = mapstr;
901

902
    if (VIR_ALLOC_N(cpuset, maxcpu) < 0) {
903
        virReportOOMError();
904 905
        goto cleanup;
    }
906
    if (virDomainCpuSetParse((const char **)&mapstr, 0,
907 908
                             cpuset, maxcpu) < 0)
        goto cleanup;
909

910 911 912 913
    VIR_FREE(entry->def->cpumask);
    entry->def->cpumask = cpuset;
    entry->def->cpumasklen = maxcpu;
    cpuset = NULL;
914

915
    if (xenXMConfigSaveFile(domain->conn, entry->filename, entry->def) < 0)
916 917 918 919 920
        goto cleanup;

    ret = 0;

 cleanup:
921
    VIR_FREE(mapsave);
922
    VIR_FREE(cpuset);
D
Daniel P. Berrange 已提交
923
    xenUnifiedUnlock(priv);
924 925 926
    return (ret);
}

927 928 929 930
/*
 * Find an inactive domain based on its name
 */
virDomainPtr xenXMDomainLookupByName(virConnectPtr conn, const char *domname) {
931
    xenUnifiedPrivatePtr priv;
932
    const char *filename;
933
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
934
    virDomainPtr ret = NULL;
935

936
    if (!VIR_IS_CONNECT(conn)) {
937
        xenXMError(VIR_ERR_INVALID_CONN, __FUNCTION__);
938 939 940
        return (NULL);
    }
    if (domname == NULL) {
941
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
942 943 944
        return (NULL);
    }

945
    priv = conn->privateData;
D
Daniel P. Berrange 已提交
946
    xenUnifiedLock(priv);
947

948
    if (!xenInotifyActive(conn) && xenXMConfigCacheRefresh (conn) < 0)
D
Daniel P. Berrange 已提交
949
        goto cleanup;
950

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

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

D
Daniel P. Berrange 已提交
957 958
    if (!(ret = virGetDomain(conn, domname, entry->def->uuid)))
        goto cleanup;
959 960 961

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

D
Daniel P. Berrange 已提交
964 965
cleanup:
    xenUnifiedUnlock(priv);
966 967 968 969 970 971 972
    return (ret);
}


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

977
    if (!memcmp(entry->def->uuid, wantuuid, VIR_UUID_BUFLEN))
978 979 980 981 982 983 984 985 986 987
        return (1);

    return (0);
}

/*
 * Find an inactive domain based on its UUID
 */
virDomainPtr xenXMDomainLookupByUUID(virConnectPtr conn,
                                     const unsigned char *uuid) {
988
    xenUnifiedPrivatePtr priv;
989
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
990
    virDomainPtr ret = NULL;
991 992

    if (!VIR_IS_CONNECT(conn)) {
993
        xenXMError(VIR_ERR_INVALID_CONN, __FUNCTION__);
994 995 996
        return (NULL);
    }
    if (uuid == NULL) {
997
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
998 999 1000
        return (NULL);
    }

1001
    priv = conn->privateData;
D
Daniel P. Berrange 已提交
1002
    xenUnifiedLock(priv);
1003

1004
    if (!xenInotifyActive(conn) && xenXMConfigCacheRefresh (conn) < 0)
D
Daniel P. Berrange 已提交
1005
        goto cleanup;
1006

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

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

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

D
Daniel P. Berrange 已提交
1017 1018
cleanup:
    xenUnifiedUnlock(priv);
1019 1020 1021 1022 1023 1024 1025 1026 1027
    return (ret);
}


/*
 * Start a domain from an existing defined config file
 */
int xenXMDomainCreate(virDomainPtr domain) {
    char *sexpr;
D
Daniel P. Berrange 已提交
1028
    int ret = -1;
1029
    xenUnifiedPrivatePtr priv;
1030 1031 1032 1033
    const char *filename;
    xenXMConfCachePtr entry;

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

1035
    if (domain->id != -1)
1036 1037
        return (-1);

D
Daniel P. Berrange 已提交
1038 1039
    xenUnifiedLock(priv);

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

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

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

1049
    ret = xenDaemonDomainCreateXML(domain->conn, sexpr);
1050
    VIR_FREE(sexpr);
D
Daniel P. Berrange 已提交
1051 1052
    if (ret != 0)
        goto error;
1053

1054
    if ((ret = xenDaemonDomainLookupByName_ids(domain->conn, domain->name,
D
Daniel P. Berrange 已提交
1055 1056
                                               entry->def->uuid)) < 0)
        goto error;
1057
    domain->id = ret;
1058

1059
    if (xend_wait_for_devices(domain->conn, domain->name) < 0)
D
Daniel P. Berrange 已提交
1060
        goto error;
1061

1062
    if (xenDaemonDomainResume(domain) < 0)
D
Daniel P. Berrange 已提交
1063
        goto error;
1064

D
Daniel P. Berrange 已提交
1065
    xenUnifiedUnlock(priv);
1066 1067
    return (0);

D
Daniel P. Berrange 已提交
1068
 error:
1069
    if (domain->id != -1) {
1070
        xenDaemonDomainDestroy(domain);
1071
        domain->id = -1;
1072
    }
D
Daniel P. Berrange 已提交
1073
    xenUnifiedUnlock(priv);
1074
    return (-1);
1075 1076
}

1077 1078 1079 1080
/*
 * Create a config file for a domain, based on an XML
 * document describing its config
 */
1081 1082
virDomainPtr xenXMDomainDefineXML(virConnectPtr conn, const char *xml)
{
1083
    virDomainPtr ret;
1084 1085
    char *filename;
    const char *oldfilename;
1086
    virDomainDefPtr def = NULL;
1087
    xenXMConfCachePtr entry = NULL;
1088
    xenUnifiedPrivatePtr priv = (xenUnifiedPrivatePtr) conn->privateData;
1089 1090

    if (!VIR_IS_CONNECT(conn)) {
1091
        xenXMError(VIR_ERR_INVALID_CONN, __FUNCTION__);
1092 1093 1094
        return (NULL);
    }
    if (xml == NULL) {
1095
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
1096 1097 1098 1099 1100
        return (NULL);
    }
    if (conn->flags & VIR_CONNECT_RO)
        return (NULL);

D
Daniel P. Berrange 已提交
1101 1102
    xenUnifiedLock(priv);

1103
    if (!xenInotifyActive(conn) && xenXMConfigCacheRefresh (conn) < 0) {
D
Daniel P. Berrange 已提交
1104
        xenUnifiedUnlock(priv);
1105
        return (NULL);
D
Daniel P. Berrange 已提交
1106
    }
1107

1108
    if (!(def = virDomainDefParseString(priv->caps, xml,
M
Matthias Bolte 已提交
1109
                                        1 << VIR_DOMAIN_VIRT_XEN,
D
Daniel P. Berrange 已提交
1110
                                        VIR_DOMAIN_XML_INACTIVE))) {
1111
        xenUnifiedUnlock(priv);
1112
        return (NULL);
D
Daniel P. Berrange 已提交
1113
    }
1114

1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
    /*
     * 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);
1126
            xenXMError(VIR_ERR_OPERATION_FAILED,
1127 1128 1129 1130 1131 1132 1133 1134
                       _("domain '%s' is already defined with uuid %s"),
                       entry->def->name, uuidstr);
            entry = NULL;
            goto error;
        }
        entry = NULL;
    }

1135
    if (virHashLookup(priv->nameConfigMap, def->name)) {
1136 1137
        /* domain exists, we will overwrite it */

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

1144
        if (!(entry = virHashLookup(priv->configCache, oldfilename))) {
1145
            xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1146
                       "%s", _("can't retrieve config entry for domain to overwrite"));
1147 1148 1149 1150
            goto error;
        }

        /* Remove the name -> filename mapping */
1151
        if (virHashRemoveEntry(priv->nameConfigMap, def->name) < 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;
        }

        /* Remove the config record itself */
1158
        if (virHashRemoveEntry(priv->configCache, oldfilename) < 0) {
1159
            xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1160
                       "%s", _("failed to remove old domain from config map"));
1161 1162 1163 1164
            goto error;
        }

        entry = NULL;
1165
    }
1166

1167
    if (!(filename = virFileBuildPath(priv->configDir, def->name, NULL)))
1168 1169
        goto error;

1170
    if (xenXMConfigSaveFile(conn, filename, def) < 0)
1171 1172
        goto error;

1173
    if (VIR_ALLOC(entry) < 0) {
1174
        virReportOOMError();
1175
        goto error;
1176
    }
1177

1178
    if ((entry->refreshedAt = time(NULL)) == ((time_t)-1)) {
1179
        xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1180
                   "%s", _("unable to get current time"));
1181
        goto error;
1182
    }
1183

E
Eric Blake 已提交
1184 1185 1186 1187
    if ((entry->filename = strdup(filename)) == NULL) {
        virReportOOMError();
        goto error;
    }
1188
    entry->def = def;
1189

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

1196
    if (virHashAddEntry(priv->nameConfigMap, def->name, entry->filename) < 0) {
1197
        virHashSteal(priv->configCache, filename);
1198
        xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1199
                   "%s", _("unable to store config file handle"));
1200
        goto error;
1201 1202
    }

1203
    ret = virGetDomain(conn, def->name, def->uuid);
D
Daniel P. Berrange 已提交
1204
    xenUnifiedUnlock(priv);
1205
    VIR_FREE(filename);
1206 1207 1208
    return (ret);

 error:
1209
    VIR_FREE(filename);
E
Eric Blake 已提交
1210
    VIR_FREE(entry->filename);
1211
    VIR_FREE(entry);
1212
    virDomainDefFree(def);
D
Daniel P. Berrange 已提交
1213
    xenUnifiedUnlock(priv);
1214 1215 1216 1217 1218 1219 1220
    return (NULL);
}

/*
 * Delete a domain from disk
 */
int xenXMDomainUndefine(virDomainPtr domain) {
1221
    xenUnifiedPrivatePtr priv;
1222
    const char *filename;
1223
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
1224 1225
    int ret = -1;

1226
    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
1227
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
1228 1229 1230
        return (-1);
    }

1231
    if (domain->id != -1)
1232 1233 1234 1235
        return (-1);
    if (domain->conn->flags & VIR_CONNECT_RO)
        return (-1);

1236
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
1237
    xenUnifiedLock(priv);
1238 1239

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

1242
    if (!(entry = virHashLookup(priv->configCache, filename)))
D
Daniel P. Berrange 已提交
1243
        goto cleanup;
1244 1245

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

1248
    /* Remove the name -> filename mapping */
1249
    if (virHashRemoveEntry(priv->nameConfigMap, domain->name) < 0)
D
Daniel P. Berrange 已提交
1250
        goto cleanup;
1251

1252
    /* Remove the config record itself */
1253
    if (virHashRemoveEntry(priv->configCache, entry->filename) < 0)
D
Daniel P. Berrange 已提交
1254
        goto cleanup;
1255

D
Daniel P. Berrange 已提交
1256 1257 1258 1259 1260
    ret = 0;

cleanup:
    xenUnifiedUnlock(priv);
    return ret;
1261 1262 1263 1264
}

struct xenXMListIteratorContext {
    virConnectPtr conn;
1265
    int oom;
1266 1267
    int max;
    int count;
1268
    char ** names;
1269 1270
};

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

1275 1276 1277
    if (ctx->oom)
        return;

1278 1279 1280
    if (ctx->count == ctx->max)
        return;

1281
    dom = xenDaemonLookupByName(ctx->conn, name);
1282
    if (!dom) {
1283 1284 1285 1286
        if (!(ctx->names[ctx->count] = strdup(name)))
            ctx->oom = 1;
        else
            ctx->count++;
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
    } else {
        virDomainFree(dom);
    }
}


/*
 * List all defined domains, filtered to remove any which
 * are currently running
 */
1297
int xenXMListDefinedDomains(virConnectPtr conn, char **const names, int maxnames) {
1298
    xenUnifiedPrivatePtr priv;
1299
    struct xenXMListIteratorContext ctx;
1300
    int i, ret = -1;
1301 1302

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

1307
    priv = conn->privateData;
D
Daniel P. Berrange 已提交
1308
    xenUnifiedLock(priv);
1309

1310
    if (!xenInotifyActive(conn) && xenXMConfigCacheRefresh (conn) < 0)
D
Daniel P. Berrange 已提交
1311
        goto cleanup;
1312

1313 1314
    if (maxnames > virHashSize(priv->configCache))
        maxnames = virHashSize(priv->configCache);
1315 1316

    ctx.conn = conn;
1317
    ctx.oom = 0;
1318 1319 1320 1321
    ctx.count = 0;
    ctx.max = maxnames;
    ctx.names = names;

1322
    virHashForEach(priv->nameConfigMap, xenXMListIterator, &ctx);
1323 1324 1325 1326 1327

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

1328
        virReportOOMError();
1329 1330 1331
        goto cleanup;
    }

D
Daniel P. Berrange 已提交
1332 1333 1334 1335 1336
    ret = ctx.count;

cleanup:
    xenUnifiedUnlock(priv);
    return ret;
1337 1338 1339 1340 1341 1342 1343
}

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

1347
    if (!VIR_IS_CONNECT(conn)) {
1348
        xenXMError(VIR_ERR_INVALID_CONN, __FUNCTION__);
1349 1350 1351
        return (-1);
    }

1352
    priv = conn->privateData;
D
Daniel P. Berrange 已提交
1353
    xenUnifiedLock(priv);
1354

1355
    if (!xenInotifyActive(conn) && xenXMConfigCacheRefresh (conn) < 0)
D
Daniel P. Berrange 已提交
1356
        goto cleanup;
1357

D
Daniel P. Berrange 已提交
1358 1359 1360 1361 1362
    ret = virHashSize(priv->nameConfigMap);

cleanup:
    xenUnifiedUnlock(priv);
    return ret;
1363 1364
}

1365

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

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

1394
    if (domain->conn->flags & VIR_CONNECT_RO)
1395
        return -1;
1396 1397 1398 1399 1400

    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) ||
        (domain->id != -1 && (flags & VIR_DOMAIN_DEVICE_MODIFY_CURRENT))) {
        xenXMError(VIR_ERR_OPERATION_INVALID, "%s",
                   _("Xm driver only supports modifying persistent config"));
1401
        return -1;
1402
    }
1403

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

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

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

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

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

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

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

    ret = 0;

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


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

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


1490
    if (domain->conn->flags & VIR_CONNECT_RO)
1491
        return -1;
1492 1493 1494 1495 1496

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

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

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

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

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

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

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

    ret = 0;

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

R
Richard W.M. Jones 已提交
1573
int
1574
xenXMDomainBlockPeek (virDomainPtr dom ATTRIBUTE_UNUSED,
R
Richard W.M. Jones 已提交
1575 1576 1577 1578 1579
                      const char *path ATTRIBUTE_UNUSED,
                      unsigned long long offset ATTRIBUTE_UNUSED,
                      size_t size ATTRIBUTE_UNUSED,
                      void *buffer ATTRIBUTE_UNUSED)
{
1580
    xenXMError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
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;
}