xm_internal.c 46.3 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,
E
Eric Blake 已提交
445
           unsigned int flags)
446
{
447 448
    xenUnifiedPrivatePtr priv = conn->privateData;

E
Eric Blake 已提交
449 450
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

451 452
    priv->configDir = XM_CONFIG_DIR;

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

    return (0);
}

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

477 478
    virHashFree(priv->nameConfigMap);
    virHashFree(priv->configCache);
479

480 481 482
    return (0);
}

483 484 485 486 487 488 489
/*
 * Since these are all offline domains, the state is always SHUTOFF.
 */
int
xenXMDomainGetState(virDomainPtr domain,
                    int *state,
                    int *reason,
E
Eric Blake 已提交
490
                    unsigned int flags)
491
{
E
Eric Blake 已提交
492 493
    virCheckFlags(0, -1);

494 495 496 497 498 499 500 501 502 503 504
    if (domain->id != -1)
        return -1;

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

    return 0;
}


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

518
    if (domain->id != -1)
519 520
        return (-1);

521
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
522
    xenUnifiedLock(priv);
523 524

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

527
    if (!(entry = virHashLookup(priv->configCache, filename)))
D
Daniel P. Berrange 已提交
528
        goto error;
529 530

    memset(info, 0, sizeof(virDomainInfo));
531 532
    info->maxMem = entry->def->mem.max_balloon;
    info->memory = entry->def->mem.cur_balloon;
533
    info->nrVirtCpu = entry->def->vcpus;
534 535 536
    info->state = VIR_DOMAIN_SHUTOFF;
    info->cpuTime = 0;

D
Daniel P. Berrange 已提交
537
    xenUnifiedUnlock(priv);
538 539
    return (0);

D
Daniel P. Berrange 已提交
540 541 542
error:
    xenUnifiedUnlock(priv);
    return -1;
543 544 545
}


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

E
Eric Blake 已提交
557 558
    /* Flags checked by virDomainDefFormat */

559
    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
560
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
561 562
        return(NULL);
    }
563
    if (domain->id != -1)
564 565
        return (NULL);

566
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
567
    xenUnifiedLock(priv);
568 569

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

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

575
    ret = virDomainDefFormat(entry->def, flags);
576

D
Daniel P. Berrange 已提交
577 578 579
cleanup:
    xenUnifiedUnlock(priv);
    return ret;
580 581 582
}


583 584 585 586
/*
 * Update amount of memory in the config file
 */
int xenXMDomainSetMemory(virDomainPtr domain, unsigned long memory) {
587
    xenUnifiedPrivatePtr priv;
588
    const char *filename;
589
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
590
    int ret = -1;
591 592

    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
593
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
594 595 596 597
        return (-1);
    }
    if (domain->conn->flags & VIR_CONNECT_RO)
        return (-1);
598
    if (domain->id != -1)
599
        return (-1);
600 601
    if (memory < 1024 * MIN_XEN_GUEST_SIZE)
        return (-1);
602

603
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
604
    xenUnifiedLock(priv);
605 606

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

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

612 613 614
    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;
615 616 617 618

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

D
Daniel P. Berrange 已提交
623 624 625
cleanup:
    xenUnifiedUnlock(priv);
    return ret;
626 627 628 629 630 631
}

/*
 * Update maximum memory limit in config
 */
int xenXMDomainSetMaxMemory(virDomainPtr domain, unsigned long memory) {
632
    xenUnifiedPrivatePtr priv;
633
    const char *filename;
634
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
635
    int ret = -1;
636 637

    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
638
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
639 640 641 642
        return (-1);
    }
    if (domain->conn->flags & VIR_CONNECT_RO)
        return (-1);
643
    if (domain->id != -1)
644 645
        return (-1);

646
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
647
    xenUnifiedLock(priv);
648 649

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

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

655 656 657
    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;
658 659 660 661

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

D
Daniel P. Berrange 已提交
666 667 668
cleanup:
    xenUnifiedUnlock(priv);
    return ret;
669 670 671 672 673 674
}

/*
 * Get max memory limit from config
 */
unsigned long xenXMDomainGetMaxMemory(virDomainPtr domain) {
675
    xenUnifiedPrivatePtr priv;
676
    const char *filename;
677
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
678
    unsigned long ret = 0;
679 680

    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
681
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
D
Daniel P. Berrange 已提交
682
        return (0);
683
    }
684
    if (domain->id != -1)
D
Daniel P. Berrange 已提交
685
        return (0);
686

687
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
688
    xenUnifiedLock(priv);
689 690

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

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

696
    ret = entry->def->mem.max_balloon;
697

D
Daniel P. Berrange 已提交
698 699 700
cleanup:
    xenUnifiedUnlock(priv);
    return ret;
701 702
}

703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
/*
 * xenXMDomainSetVcpusFlags:
 * @domain: pointer to domain object
 * @nvcpus: number of vcpus
 * @flags: bitwise-ORd from virDomainVcpuFlags
 *
 * Change virtual CPUs allocation of domain according to flags.
 *
 * Returns 0 on success, -1 if an error message was issued, and -2 if
 * the unified driver should keep trying.
 */
int
xenXMDomainSetVcpusFlags(virDomainPtr domain, unsigned int vcpus,
                         unsigned int flags)
{
    xenUnifiedPrivatePtr priv;
    const char *filename;
    xenXMConfCachePtr entry;
    int ret = -1;
    int max;

E
Eric Blake 已提交
724 725 726 727
    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
                  VIR_DOMAIN_VCPU_CONFIG |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

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 768 769 770 771 772 773 774 775 776 777 778
    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
779 780
     * in-memory representation of the config file. I say not!
     */
781
    if (xenXMConfigSaveFile(domain->conn, entry->filename, entry->def) < 0)
D
Daniel P. Berrange 已提交
782 783
        goto cleanup;
    ret = 0;
784

D
Daniel P. Berrange 已提交
785 786 787
cleanup:
    xenUnifiedUnlock(priv);
    return ret;
788 789
}

790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
/**
 * xenXMDomainGetVcpusFlags:
 * @domain: pointer to domain object
 * @flags: bitwise-ORd from virDomainVcpuFlags
 *
 * Extract information about virtual CPUs of domain according to flags.
 *
 * Returns the number of vcpus on success, -1 if an error message was
 * issued, and -2 if the unified driver should keep trying.
 */
int
xenXMDomainGetVcpusFlags(virDomainPtr domain, unsigned int flags)
{
    xenUnifiedPrivatePtr priv;
    const char *filename;
    xenXMConfCachePtr entry;
    int ret = -2;

E
Eric Blake 已提交
808 809 810 811
    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
                  VIR_DOMAIN_VCPU_CONFIG |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
    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;
}

841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
/**
 * 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)
{
856
    xenUnifiedPrivatePtr priv;
857 858
    const char *filename;
    xenXMConfCachePtr entry;
859
    virBuffer mapbuf = VIR_BUFFER_INITIALIZER;
860
    char *mapstr = NULL, *mapsave = NULL;
861 862
    int i, j, n, comma = 0;
    int ret = -1;
863 864
    char *cpuset = NULL;
    int maxcpu = XEN_MAX_PHYSICAL_CPU;
865 866 867

    if (domain == NULL || domain->conn == NULL || domain->name == NULL
        || cpumap == NULL || maplen < 1 || maplen > (int)sizeof(cpumap_t)) {
868
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
869 870 871
        return -1;
    }
    if (domain->conn->flags & VIR_CONNECT_RO) {
872
        xenXMError(VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
873
                    "%s", _("read only connection"));
874 875 876
        return -1;
    }
    if (domain->id != -1) {
877
        xenXMError(VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
878
                    "%s", _("not inactive domain"));
879 880 881
        return -1;
    }

882
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
883
    xenUnifiedLock(priv);
884 885

    if (!(filename = virHashLookup(priv->nameConfigMap, domain->name))) {
886
        xenXMError(VIR_ERR_INTERNAL_ERROR, "%s", _("virHashLookup"));
D
Daniel P. Berrange 已提交
887
        goto cleanup;
888
    }
889
    if (!(entry = virHashLookup(priv->configCache, filename))) {
890
        xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
891
                    "%s", _("can't retrieve config file for domain"));
D
Daniel P. Berrange 已提交
892
        goto cleanup;
893 894 895 896 897 898 899 900
    }

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

901 902
                if (comma)
                    virBufferAddLit (&mapbuf, ",");
903 904
                comma = 1;

905
                virBufferAsprintf (&mapbuf, "%d", n);
906 907
            }

908
    if (virBufferError(&mapbuf)) {
909
        virBufferFreeAndReset(&mapbuf);
910
        virReportOOMError();
D
Daniel P. Berrange 已提交
911
        goto cleanup;
912 913 914
    }

    mapstr = virBufferContentAndReset(&mapbuf);
915
    mapsave = mapstr;
916

917
    if (VIR_ALLOC_N(cpuset, maxcpu) < 0) {
918
        virReportOOMError();
919 920
        goto cleanup;
    }
921
    if (virDomainCpuSetParse((const char **)&mapstr, 0,
922 923
                             cpuset, maxcpu) < 0)
        goto cleanup;
924

925 926 927 928
    VIR_FREE(entry->def->cpumask);
    entry->def->cpumask = cpuset;
    entry->def->cpumasklen = maxcpu;
    cpuset = NULL;
929

930
    if (xenXMConfigSaveFile(domain->conn, entry->filename, entry->def) < 0)
931 932 933 934 935
        goto cleanup;

    ret = 0;

 cleanup:
936
    VIR_FREE(mapsave);
937
    VIR_FREE(cpuset);
D
Daniel P. Berrange 已提交
938
    xenUnifiedUnlock(priv);
939 940 941
    return (ret);
}

942 943 944 945
/*
 * Find an inactive domain based on its name
 */
virDomainPtr xenXMDomainLookupByName(virConnectPtr conn, const char *domname) {
946
    xenUnifiedPrivatePtr priv;
947
    const char *filename;
948
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
949
    virDomainPtr ret = NULL;
950

951
    if (!VIR_IS_CONNECT(conn)) {
952
        xenXMError(VIR_ERR_INVALID_CONN, __FUNCTION__);
953 954 955
        return (NULL);
    }
    if (domname == NULL) {
956
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
957 958 959
        return (NULL);
    }

960
    priv = conn->privateData;
D
Daniel P. Berrange 已提交
961
    xenUnifiedLock(priv);
962

963
    if (!xenInotifyActive(conn) && xenXMConfigCacheRefresh (conn) < 0)
D
Daniel P. Berrange 已提交
964
        goto cleanup;
965

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

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

D
Daniel P. Berrange 已提交
972 973
    if (!(ret = virGetDomain(conn, domname, entry->def->uuid)))
        goto cleanup;
974 975 976

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

D
Daniel P. Berrange 已提交
979 980
cleanup:
    xenUnifiedUnlock(priv);
981 982 983 984 985 986 987
    return (ret);
}


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

992
    if (!memcmp(entry->def->uuid, wantuuid, VIR_UUID_BUFLEN))
993 994 995 996 997 998 999 1000 1001 1002
        return (1);

    return (0);
}

/*
 * Find an inactive domain based on its UUID
 */
virDomainPtr xenXMDomainLookupByUUID(virConnectPtr conn,
                                     const unsigned char *uuid) {
1003
    xenUnifiedPrivatePtr priv;
1004
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
1005
    virDomainPtr ret = NULL;
1006 1007

    if (!VIR_IS_CONNECT(conn)) {
1008
        xenXMError(VIR_ERR_INVALID_CONN, __FUNCTION__);
1009 1010 1011
        return (NULL);
    }
    if (uuid == NULL) {
1012
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
1013 1014 1015
        return (NULL);
    }

1016
    priv = conn->privateData;
D
Daniel P. Berrange 已提交
1017
    xenUnifiedLock(priv);
1018

1019
    if (!xenInotifyActive(conn) && xenXMConfigCacheRefresh (conn) < 0)
D
Daniel P. Berrange 已提交
1020
        goto cleanup;
1021

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

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

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

D
Daniel P. Berrange 已提交
1032 1033
cleanup:
    xenUnifiedUnlock(priv);
1034 1035 1036 1037 1038 1039 1040 1041 1042
    return (ret);
}


/*
 * Start a domain from an existing defined config file
 */
int xenXMDomainCreate(virDomainPtr domain) {
    char *sexpr;
D
Daniel P. Berrange 已提交
1043
    int ret = -1;
1044
    xenUnifiedPrivatePtr priv;
1045 1046 1047 1048
    const char *filename;
    xenXMConfCachePtr entry;

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

1050
    if (domain->id != -1)
1051 1052
        return (-1);

D
Daniel P. Berrange 已提交
1053 1054
    xenUnifiedLock(priv);

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

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

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

1064
    ret = xenDaemonDomainCreateXML(domain->conn, sexpr);
1065
    VIR_FREE(sexpr);
D
Daniel P. Berrange 已提交
1066 1067
    if (ret != 0)
        goto error;
1068

1069
    if ((ret = xenDaemonDomainLookupByName_ids(domain->conn, domain->name,
D
Daniel P. Berrange 已提交
1070 1071
                                               entry->def->uuid)) < 0)
        goto error;
1072
    domain->id = ret;
1073

1074
    if (xend_wait_for_devices(domain->conn, domain->name) < 0)
D
Daniel P. Berrange 已提交
1075
        goto error;
1076

1077
    if (xenDaemonDomainResume(domain) < 0)
D
Daniel P. Berrange 已提交
1078
        goto error;
1079

D
Daniel P. Berrange 已提交
1080
    xenUnifiedUnlock(priv);
1081 1082
    return (0);

D
Daniel P. Berrange 已提交
1083
 error:
1084
    if (domain->id != -1) {
1085
        xenDaemonDomainDestroy(domain);
1086
        domain->id = -1;
1087
    }
D
Daniel P. Berrange 已提交
1088
    xenUnifiedUnlock(priv);
1089
    return (-1);
1090 1091
}

1092 1093 1094 1095
/*
 * Create a config file for a domain, based on an XML
 * document describing its config
 */
1096 1097
virDomainPtr xenXMDomainDefineXML(virConnectPtr conn, const char *xml)
{
1098
    virDomainPtr ret;
1099 1100
    char *filename;
    const char *oldfilename;
1101
    virDomainDefPtr def = NULL;
1102
    xenXMConfCachePtr entry = NULL;
1103
    xenUnifiedPrivatePtr priv = (xenUnifiedPrivatePtr) conn->privateData;
1104 1105

    if (!VIR_IS_CONNECT(conn)) {
1106
        xenXMError(VIR_ERR_INVALID_CONN, __FUNCTION__);
1107 1108 1109
        return (NULL);
    }
    if (xml == NULL) {
1110
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
1111 1112 1113 1114 1115
        return (NULL);
    }
    if (conn->flags & VIR_CONNECT_RO)
        return (NULL);

D
Daniel P. Berrange 已提交
1116 1117
    xenUnifiedLock(priv);

1118
    if (!xenInotifyActive(conn) && xenXMConfigCacheRefresh (conn) < 0) {
D
Daniel P. Berrange 已提交
1119
        xenUnifiedUnlock(priv);
1120
        return (NULL);
D
Daniel P. Berrange 已提交
1121
    }
1122

1123
    if (!(def = virDomainDefParseString(priv->caps, xml,
M
Matthias Bolte 已提交
1124
                                        1 << VIR_DOMAIN_VIRT_XEN,
D
Daniel P. Berrange 已提交
1125
                                        VIR_DOMAIN_XML_INACTIVE))) {
1126
        xenUnifiedUnlock(priv);
1127
        return (NULL);
D
Daniel P. Berrange 已提交
1128
    }
1129

1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
    /*
     * 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);
1141
            xenXMError(VIR_ERR_OPERATION_FAILED,
1142 1143 1144 1145 1146 1147 1148 1149
                       _("domain '%s' is already defined with uuid %s"),
                       entry->def->name, uuidstr);
            entry = NULL;
            goto error;
        }
        entry = NULL;
    }

1150
    if (virHashLookup(priv->nameConfigMap, def->name)) {
1151 1152
        /* domain exists, we will overwrite it */

1153
        if (!(oldfilename = (char *)virHashLookup(priv->nameConfigMap, def->name))) {
1154
            xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1155
                       "%s", _("can't retrieve config filename for domain to overwrite"));
1156 1157 1158
            goto error;
        }

1159
        if (!(entry = virHashLookup(priv->configCache, oldfilename))) {
1160
            xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1161
                       "%s", _("can't retrieve config entry for domain to overwrite"));
1162 1163 1164 1165
            goto error;
        }

        /* Remove the name -> filename mapping */
1166
        if (virHashRemoveEntry(priv->nameConfigMap, def->name) < 0) {
1167
            xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1168
                       "%s", _("failed to remove old domain from config map"));
1169 1170 1171 1172
            goto error;
        }

        /* Remove the config record itself */
1173
        if (virHashRemoveEntry(priv->configCache, oldfilename) < 0) {
1174
            xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1175
                       "%s", _("failed to remove old domain from config map"));
1176 1177 1178 1179
            goto error;
        }

        entry = NULL;
1180
    }
1181

1182
    if (!(filename = virFileBuildPath(priv->configDir, def->name, NULL)))
1183 1184
        goto error;

1185
    if (xenXMConfigSaveFile(conn, filename, def) < 0)
1186 1187
        goto error;

1188
    if (VIR_ALLOC(entry) < 0) {
1189
        virReportOOMError();
1190
        goto error;
1191
    }
1192

1193
    if ((entry->refreshedAt = time(NULL)) == ((time_t)-1)) {
1194
        xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1195
                   "%s", _("unable to get current time"));
1196
        goto error;
1197
    }
1198

E
Eric Blake 已提交
1199 1200 1201 1202
    if ((entry->filename = strdup(filename)) == NULL) {
        virReportOOMError();
        goto error;
    }
1203
    entry->def = def;
1204

1205
    if (virHashAddEntry(priv->configCache, filename, entry) < 0) {
1206
        xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1207
                   "%s", _("unable to store config file handle"));
1208
        goto error;
1209
    }
1210

1211
    if (virHashAddEntry(priv->nameConfigMap, def->name, entry->filename) < 0) {
1212
        virHashSteal(priv->configCache, filename);
1213
        xenXMError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1214
                   "%s", _("unable to store config file handle"));
1215
        goto error;
1216 1217
    }

1218
    ret = virGetDomain(conn, def->name, def->uuid);
D
Daniel P. Berrange 已提交
1219
    xenUnifiedUnlock(priv);
1220
    VIR_FREE(filename);
1221 1222 1223
    return (ret);

 error:
1224
    VIR_FREE(filename);
E
Eric Blake 已提交
1225
    VIR_FREE(entry->filename);
1226
    VIR_FREE(entry);
1227
    virDomainDefFree(def);
D
Daniel P. Berrange 已提交
1228
    xenUnifiedUnlock(priv);
1229 1230 1231 1232 1233 1234 1235
    return (NULL);
}

/*
 * Delete a domain from disk
 */
int xenXMDomainUndefine(virDomainPtr domain) {
1236
    xenUnifiedPrivatePtr priv;
1237
    const char *filename;
1238
    xenXMConfCachePtr entry;
D
Daniel P. Berrange 已提交
1239 1240
    int ret = -1;

1241
    if ((domain == NULL) || (domain->conn == NULL) || (domain->name == NULL)) {
1242
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
1243 1244 1245
        return (-1);
    }

1246
    if (domain->id != -1)
1247 1248 1249 1250
        return (-1);
    if (domain->conn->flags & VIR_CONNECT_RO)
        return (-1);

1251
    priv = domain->conn->privateData;
D
Daniel P. Berrange 已提交
1252
    xenUnifiedLock(priv);
1253 1254

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

1257
    if (!(entry = virHashLookup(priv->configCache, filename)))
D
Daniel P. Berrange 已提交
1258
        goto cleanup;
1259 1260

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

1263
    /* Remove the name -> filename mapping */
1264
    if (virHashRemoveEntry(priv->nameConfigMap, domain->name) < 0)
D
Daniel P. Berrange 已提交
1265
        goto cleanup;
1266

1267
    /* Remove the config record itself */
1268
    if (virHashRemoveEntry(priv->configCache, entry->filename) < 0)
D
Daniel P. Berrange 已提交
1269
        goto cleanup;
1270

D
Daniel P. Berrange 已提交
1271 1272 1273 1274 1275
    ret = 0;

cleanup:
    xenUnifiedUnlock(priv);
    return ret;
1276 1277 1278 1279
}

struct xenXMListIteratorContext {
    virConnectPtr conn;
1280
    int oom;
1281 1282
    int max;
    int count;
1283
    char ** names;
1284 1285
};

1286
static void xenXMListIterator(void *payload ATTRIBUTE_UNUSED, const void *name, void *data) {
1287
    struct xenXMListIteratorContext *ctx = data;
1288 1289
    virDomainPtr dom = NULL;

1290 1291 1292
    if (ctx->oom)
        return;

1293 1294 1295
    if (ctx->count == ctx->max)
        return;

1296
    dom = xenDaemonLookupByName(ctx->conn, name);
1297
    if (!dom) {
1298 1299 1300 1301
        if (!(ctx->names[ctx->count] = strdup(name)))
            ctx->oom = 1;
        else
            ctx->count++;
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
    } else {
        virDomainFree(dom);
    }
}


/*
 * List all defined domains, filtered to remove any which
 * are currently running
 */
1312
int xenXMListDefinedDomains(virConnectPtr conn, char **const names, int maxnames) {
1313
    xenUnifiedPrivatePtr priv;
1314
    struct xenXMListIteratorContext ctx;
1315
    int i, ret = -1;
1316 1317

    if (!VIR_IS_CONNECT(conn)) {
1318
        xenXMError(VIR_ERR_INVALID_CONN, __FUNCTION__);
1319 1320 1321
        return (-1);
    }

1322
    priv = conn->privateData;
D
Daniel P. Berrange 已提交
1323
    xenUnifiedLock(priv);
1324

1325
    if (!xenInotifyActive(conn) && xenXMConfigCacheRefresh (conn) < 0)
D
Daniel P. Berrange 已提交
1326
        goto cleanup;
1327

1328 1329
    if (maxnames > virHashSize(priv->configCache))
        maxnames = virHashSize(priv->configCache);
1330 1331

    ctx.conn = conn;
1332
    ctx.oom = 0;
1333 1334 1335 1336
    ctx.count = 0;
    ctx.max = maxnames;
    ctx.names = names;

1337
    virHashForEach(priv->nameConfigMap, xenXMListIterator, &ctx);
1338 1339 1340 1341 1342

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

1343
        virReportOOMError();
1344 1345 1346
        goto cleanup;
    }

D
Daniel P. Berrange 已提交
1347 1348 1349 1350 1351
    ret = ctx.count;

cleanup:
    xenUnifiedUnlock(priv);
    return ret;
1352 1353 1354 1355 1356 1357 1358
}

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

1362
    if (!VIR_IS_CONNECT(conn)) {
1363
        xenXMError(VIR_ERR_INVALID_CONN, __FUNCTION__);
1364 1365 1366
        return (-1);
    }

1367
    priv = conn->privateData;
D
Daniel P. Berrange 已提交
1368
    xenUnifiedLock(priv);
1369

1370
    if (!xenInotifyActive(conn) && xenXMConfigCacheRefresh (conn) < 0)
D
Daniel P. Berrange 已提交
1371
        goto cleanup;
1372

D
Daniel P. Berrange 已提交
1373 1374 1375 1376 1377
    ret = virHashSize(priv->nameConfigMap);

cleanup:
    xenUnifiedUnlock(priv);
    return ret;
1378 1379
}

1380

1381
/**
1382
 * xenXMDomainAttachDeviceFlags:
1383 1384
 * @domain: pointer to domain object
 * @xml: pointer to XML description of device
1385
 * @flags: an OR'ed set of virDomainDeviceModifyFlags
J
Jim Meyering 已提交
1386
 *
1387 1388
 * Create a virtual device attachment to backend.
 * XML description is translated into config file.
1389 1390
 * This driver only supports device allocation to
 * persisted config.
J
Jim Meyering 已提交
1391
 *
1392 1393 1394
 * Returns 0 in case of success, -1 in case of failure.
 */
static int
1395
xenXMDomainAttachDeviceFlags(virDomainPtr domain, const char *xml,
E
Eric Blake 已提交
1396 1397
                             unsigned int flags)
{
1398 1399
    const char *filename = NULL;
    xenXMConfCachePtr entry = NULL;
1400 1401
    int ret = -1;
    virDomainDeviceDefPtr dev = NULL;
1402
    virDomainDefPtr def;
1403
    xenUnifiedPrivatePtr priv;
1404

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

1407
    if ((!domain) || (!domain->conn) || (!domain->name) || (!xml)) {
1408
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
1409
        return -1;
1410
    }
1411

1412
    if (domain->conn->flags & VIR_CONNECT_RO)
1413
        return -1;
1414 1415

    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) ||
E
Eric Blake 已提交
1416
        (domain->id != -1 && flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)) {
1417 1418
        xenXMError(VIR_ERR_OPERATION_INVALID, "%s",
                   _("Xm driver only supports modifying persistent config"));
1419
        return -1;
1420
    }
1421

D
Daniel P. Berrange 已提交
1422 1423 1424
    priv = (xenUnifiedPrivatePtr) domain->conn->privateData;
    xenUnifiedLock(priv);

1425
    if (!(filename = virHashLookup(priv->nameConfigMap, domain->name)))
D
Daniel P. Berrange 已提交
1426
        goto cleanup;
1427
    if (!(entry = virHashLookup(priv->configCache, filename)))
D
Daniel P. Berrange 已提交
1428
        goto cleanup;
1429
    def = entry->def;
1430

1431
    if (!(dev = virDomainDeviceDefParse(priv->caps,
1432
                                        entry->def,
G
Guido Günther 已提交
1433
                                        xml, VIR_DOMAIN_XML_INACTIVE)))
D
Daniel P. Berrange 已提交
1434
        goto cleanup;
1435

1436 1437 1438
    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
    {
1439
        if (virDomainDiskInsert(def, dev->data.disk) < 0) {
1440
            virReportOOMError();
1441
            goto cleanup;
1442 1443
        }
        dev->data.disk = NULL;
1444
    }
1445
    break;
1446

1447 1448
    case VIR_DOMAIN_DEVICE_NET:
    {
1449
        if (VIR_REALLOC_N(def->nets, def->nnets+1) < 0) {
1450
            virReportOOMError();
1451 1452 1453
            goto cleanup;
        }
        def->nets[def->nnets++] = dev->data.net;
1454 1455
        dev->data.net = NULL;
        break;
1456 1457
    }

1458
    default:
1459 1460
        xenXMError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                   _("Xm driver only supports adding disk or network devices"));
1461 1462 1463 1464 1465 1466
        goto cleanup;
    }

    /* If this fails, should we try to undo our changes to the
     * in-memory representation of the config file. I say not!
     */
1467
    if (xenXMConfigSaveFile(domain->conn, entry->filename, entry->def) < 0)
1468 1469 1470 1471 1472
        goto cleanup;

    ret = 0;

 cleanup:
1473
    virDomainDeviceDefFree(dev);
D
Daniel P. Berrange 已提交
1474
    xenUnifiedUnlock(priv);
1475 1476 1477 1478 1479
    return ret;
}


/**
1480
 * xenXMDomainDetachDeviceFlags:
1481 1482
 * @domain: pointer to domain object
 * @xml: pointer to XML description of device
1483
 * @flags: an OR'ed set of virDomainDeviceModifyFlags
J
Jim Meyering 已提交
1484
 *
1485
 * Destroy a virtual device attachment to backend.
1486 1487
 * This driver only supports device deallocation from
 * persisted config.
1488 1489 1490 1491
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
static int
1492 1493
xenXMDomainDetachDeviceFlags(virDomainPtr domain, const char *xml,
                             unsigned int flags) {
1494 1495
    const char *filename = NULL;
    xenXMConfCachePtr entry = NULL;
1496
    virDomainDeviceDefPtr dev = NULL;
1497
    virDomainDefPtr def;
1498
    int ret = -1;
1499
    int i;
1500
    xenUnifiedPrivatePtr priv;
1501

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

1504
    if ((!domain) || (!domain->conn) || (!domain->name) || (!xml)) {
1505
        xenXMError(VIR_ERR_INVALID_ARG, __FUNCTION__);
1506
        return -1;
1507
    }
1508

1509
    if (domain->conn->flags & VIR_CONNECT_RO)
1510
        return -1;
1511 1512

    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) ||
E
Eric Blake 已提交
1513
        (domain->id != -1 && flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)) {
1514 1515
        xenXMError(VIR_ERR_OPERATION_INVALID, "%s",
                   _("Xm driver only supports modifying persistent config"));
1516
        return -1;
1517
    }
D
Daniel P. Berrange 已提交
1518 1519 1520 1521

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

1522
    if (!(filename = virHashLookup(priv->nameConfigMap, domain->name)))
D
Daniel P. Berrange 已提交
1523
        goto cleanup;
1524
    if (!(entry = virHashLookup(priv->configCache, filename)))
D
Daniel P. Berrange 已提交
1525
        goto cleanup;
1526
    def = entry->def;
1527

1528
    if (!(dev = virDomainDeviceDefParse(priv->caps,
1529
                                        entry->def,
G
Guido Günther 已提交
1530
                                        xml, VIR_DOMAIN_XML_INACTIVE)))
D
Daniel P. Berrange 已提交
1531
        goto cleanup;
1532

1533 1534 1535
    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
    {
1536 1537
        for (i = 0 ; i < def->ndisks ; i++) {
            if (def->disks[i]->dst &&
1538
                dev->data.disk->dst &&
1539 1540 1541 1542 1543
                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,
1544 1545
                            sizeof(*def->disks) *
                            (def->ndisks - (i + 1)));
1546
                def->ndisks--;
1547
                break;
1548 1549
            }
        }
1550 1551 1552 1553 1554
        break;
    }

    case VIR_DOMAIN_DEVICE_NET:
    {
1555 1556 1557
        for (i = 0 ; i < def->nnets ; i++) {
            if (!memcmp(def->nets[i]->mac,
                        dev->data.net->mac,
1558
                        sizeof(def->nets[i]->mac))) {
1559 1560 1561 1562
                virDomainNetDefFree(def->nets[i]);
                if (i < (def->nnets - 1))
                    memmove(def->nets + i,
                            def->nets + i + 1,
1563 1564
                            sizeof(*def->nets) *
                            (def->nnets - (i + 1)));
1565
                def->nnets--;
1566 1567 1568 1569
                break;
            }
        }
        break;
1570
    }
1571
    default:
1572 1573 1574
        xenXMError(VIR_ERR_CONFIG_UNSUPPORTED,
                   _("device type '%s' cannot be detached"),
                   virDomainDeviceTypeToString(dev->type));
1575 1576 1577 1578 1579 1580
        goto cleanup;
    }

    /* If this fails, should we try to undo our changes to the
     * in-memory representation of the config file. I say not!
     */
1581
    if (xenXMConfigSaveFile(domain->conn, entry->filename, entry->def) < 0)
1582 1583 1584 1585 1586
        goto cleanup;

    ret = 0;

 cleanup:
1587
    virDomainDeviceDefFree(dev);
D
Daniel P. Berrange 已提交
1588
    xenUnifiedUnlock(priv);
1589 1590 1591
    return (ret);
}

R
Richard W.M. Jones 已提交
1592
int
1593
xenXMDomainBlockPeek (virDomainPtr dom ATTRIBUTE_UNUSED,
R
Richard W.M. Jones 已提交
1594 1595 1596 1597 1598
                      const char *path ATTRIBUTE_UNUSED,
                      unsigned long long offset ATTRIBUTE_UNUSED,
                      size_t size ATTRIBUTE_UNUSED,
                      void *buffer ATTRIBUTE_UNUSED)
{
1599
    xenXMError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
R
Richard W.M. Jones 已提交
1600 1601 1602
    return -1;
}

1603 1604 1605 1606

static char *xenXMAutostartLinkName(virDomainPtr dom)
{
    char *ret;
1607 1608
    if (virAsprintf(&ret, "/etc/xen/auto/%s", dom->name) < 0)
        return NULL;
1609 1610 1611 1612 1613 1614
    return ret;
}

static char *xenXMDomainConfigName(virDomainPtr dom)
{
    char *ret;
1615 1616
    if (virAsprintf(&ret, "/etc/xen/%s", dom->name) < 0)
        return NULL;
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
    return ret;
}

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

    if (!linkname || !config) {
1627
        virReportOOMError();
1628 1629 1630 1631 1632
        goto cleanup;
    }

    *autostart = virFileLinkPointsTo(linkname, config);
    if (*autostart < 0) {
1633
        virReportSystemError(errno,
1634 1635
                             _("cannot check link %s points to config %s"),
                             linkname, config);
1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
        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) {
1655
        virReportOOMError();
1656 1657 1658 1659 1660 1661
        goto cleanup;
    }

    if (autostart) {
        if (symlink(config, linkname) < 0 &&
            errno != EEXIST) {
1662
            virReportSystemError(errno,
1663 1664
                                 _("failed to create link %s to %s"),
                                 config, linkname);
1665 1666 1667 1668 1669
            goto cleanup;
        }
    } else {
        if (unlink(linkname)  < 0 &&
            errno != ENOENT) {
1670
            virReportSystemError(errno,
1671 1672
                                 _("failed to remove link %s"),
                                 linkname);
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
            goto cleanup;
        }
    }
    ret = 0;

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

    return ret;
}