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
    NULL, /* domainSuspend */
    NULL, /* domainResume */
    NULL, /* domainShutdown */
    NULL, /* domainReboot */
    NULL, /* domainDestroy */
98
    NULL, /* domainDestroyFlags */
99 100 101 102 103 104 105
    NULL, /* domainGetOSType */
    xenXMDomainGetMaxMemory, /* domainGetMaxMemory */
    xenXMDomainSetMaxMemory, /* domainSetMaxMemory */
    xenXMDomainSetMemory, /* domainMaxMemory */
    xenXMDomainGetInfo, /* domainGetInfo */
    NULL, /* domainSave */
    NULL, /* domainRestore */
D
Daniel Veillard 已提交
106
    NULL, /* domainCoreDump */
107
    NULL, /* domainScreenshot */
108
    xenXMDomainPinVcpu, /* domainPinVcpu */
109 110 111 112 113 114
    NULL, /* domainGetVcpus */
    xenXMListDefinedDomains, /* listDefinedDomains */
    xenXMNumOfDefinedDomains, /* numOfDefinedDomains */
    xenXMDomainCreate, /* domainCreate */
    xenXMDomainDefineXML, /* domainDefineXML */
    xenXMDomainUndefine, /* domainUndefine */
115 116
    xenXMDomainAttachDeviceFlags, /* domainAttachDeviceFlags */
    xenXMDomainDetachDeviceFlags, /* domainDetachDeviceFlags */
117
    NULL, /* domainUpdateDeviceFlags */
118 119
    NULL, /* domainGetAutostart */
    NULL, /* domainSetAutostart */
120 121 122
    NULL, /* domainGetSchedulerType */
    NULL, /* domainGetSchedulerParameters */
    NULL, /* domainSetSchedulerParameters */
123 124
};

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

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

142 143

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

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

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

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

174 175 176 177 178

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

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

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

    return def;
}

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

    return 0;
}
332

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

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

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

360
    priv->lastRefresh = now;
361 362

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

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

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

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

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

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

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

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

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

    return (ret);
}


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

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

452 453
    priv->configDir = XM_CONFIG_DIR;

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

    return (0);
}

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

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

481 482 483
    return (0);
}

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

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

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

    return 0;
}


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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
/*
 * 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 已提交
725 726 727 728
    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
                  VIR_DOMAIN_VCPU_CONFIG |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

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

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

791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
/**
 * 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 已提交
809 810 811 812
    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
                  VIR_DOMAIN_VCPU_CONFIG |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

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

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

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

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

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

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

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

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

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

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

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

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

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

    ret = 0;

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

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

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

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

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

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

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

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

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

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


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

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

    return (0);
}

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        entry = NULL;
1181
    }
1182

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1381

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

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

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

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

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

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

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

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

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

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

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

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

    ret = 0;

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


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

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

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

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

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

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

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

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

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

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

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

    ret = 0;

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

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

1604 1605 1606 1607

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

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

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

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

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

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

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

    return ret;
}