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,
D
Daniel P. Berrange 已提交
1109
                                        VIR_DOMAIN_XML_INACTIVE))) {
1110
        xenUnifiedUnlock(priv);
1111
        return (NULL);
D
Daniel P. Berrange 已提交
1112
    }
1113

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

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

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

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

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

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

        entry = NULL;
1164
    }
1165

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1364

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

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

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

    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"));
1400
        return -1;
1401
    }
1402

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

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

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

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

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

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

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

    ret = 0;

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


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

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


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

    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"));
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
    xenXMError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
R
Richard W.M. Jones 已提交
1580 1581 1582
    return -1;
}

1583 1584 1585 1586

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

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

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

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

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

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

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

    return ret;
}