xs_internal.c 38.3 KB
Newer Older
1 2 3
/*
 * xs_internal.c: access to Xen Store
 *
4
 * Copyright (C) 2006, 2009-2011 Red Hat, Inc.
5 6 7 8 9 10
 *
 * See COPYING.LIB for the License of this software
 *
 * Daniel Veillard <veillard@redhat.com>
 */

11
#include <config.h>
J
Jim Meyering 已提交
12

13 14 15 16 17 18 19 20 21 22
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/ioctl.h>

#include <stdint.h>

23
#include <xen/dom0_ops.h>
24 25 26 27
#include <xen/version.h>

#include <xs.h>

28
#include "virterror_internal.h"
29
#include "datatypes.h"
30
#include "driver.h"
31 32 33
#include "memory.h"
#include "logging.h"
#include "uuid.h"
34
#include "xen_driver.h"
35
#include "xs_internal.h"
36
#include "xen_hypervisor.h"
37

38 39
#define VIR_FROM_THIS VIR_FROM_XEN

40
static char *xenStoreDomainGetOSType(virDomainPtr domain);
D
Daniel P. Berrange 已提交
41 42
static void xenStoreWatchEvent(int watch, int fd, int events, void *data);
static void xenStoreWatchListFree(xenStoreWatchListPtr list);
43

44
struct xenUnifiedDriver xenStoreDriver = {
45 46 47
    xenStoreOpen, /* open */
    xenStoreClose, /* close */
    NULL, /* version */
48
    NULL, /* hostname */
49
    NULL, /* nodeGetInfo */
50
    NULL, /* getCapabilities */
51 52
    xenStoreListDomains, /* listDomains */
    NULL, /* numOfDomains */
53
    NULL, /* domainCreateXML */
54 55
    NULL, /* domainSuspend */
    NULL, /* domainResume */
56 57
    xenStoreDomainShutdown, /* domainShutdown */
    xenStoreDomainReboot, /* domainReboot */
58
    NULL, /* domainDestroy */
59
    xenStoreDomainGetOSType, /* domainGetOSType */
60
    xenStoreDomainGetMaxMemory, /* domainGetMaxMemory */
61 62
    NULL, /* domainSetMaxMemory */
    xenStoreDomainSetMemory, /* domainSetMemory */
63 64
    xenStoreGetDomainInfo, /* domainGetInfo */
    NULL, /* domainSave */
65
    NULL, /* domainRestore */
D
Daniel Veillard 已提交
66
    NULL, /* domainCoreDump */
67
    NULL, /* domainScreenshot */
68
    NULL, /* domainPinVcpu */
69
    NULL, /* domainGetVcpus */
70 71 72 73 74
    NULL, /* listDefinedDomains */
    NULL, /* numOfDefinedDomains */
    NULL, /* domainCreate */
    NULL, /* domainDefineXML */
    NULL, /* domainUndefine */
75 76
    NULL, /* domainAttachDeviceFlags */
    NULL, /* domainDetachDeviceFlags */
77
    NULL, /* domainUpdateDeviceFlags */
78 79
    NULL, /* domainGetAutostart */
    NULL, /* domainSetAutostart */
80 81 82
    NULL, /* domainGetSchedulerType */
    NULL, /* domainGetSchedulerParameters */
    NULL, /* domainSetSchedulerParameters */
83 84
};

85
#define virXenStoreError(code, ...)                                  \
86
        virReportErrorHelper(VIR_FROM_XENSTORE, code, __FILE__,      \
87
                             __FUNCTION__, __LINE__, __VA_ARGS__)
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107

/************************************************************************
 *									*
 *		Helper internal APIs					*
 *									*
 ************************************************************************/
/**
 * virConnectDoStoreList:
 * @conn: pointer to the hypervisor connection
 * @path: the absolute path of the directory in the store to list
 * @nb: OUT pointer to the number of items found
 *
 * Internal API querying the Xenstore for a list
 *
 * Returns a string which must be freed by the caller or NULL in case of error
 */
static char **
virConnectDoStoreList(virConnectPtr conn, const char *path,
                      unsigned int *nb)
{
108 109 110 111 112 113 114
    xenUnifiedPrivatePtr priv;

    if (conn == NULL)
        return NULL;

    priv = (xenUnifiedPrivatePtr) conn->privateData;
    if (priv->xshandle == NULL || path == NULL || nb == NULL)
115 116
        return (NULL);

117
    return xs_directory (priv->xshandle, 0, path, nb);
118 119 120 121
}

/**
 * virDomainDoStoreQuery:
122 123
 * @conn: pointer to the hypervisor connection
 * @domid: id of the domain
124 125 126 127 128 129 130
 * @path: the relative path of the data in the store to retrieve
 *
 * Internal API querying the Xenstore for a string value.
 *
 * Returns a string which must be freed by the caller or NULL in case of error
 */
static char *
131
virDomainDoStoreQuery(virConnectPtr conn, int domid, const char *path)
132 133 134
{
    char s[256];
    unsigned int len = 0;
135 136 137 138
    xenUnifiedPrivatePtr priv;

    if (!conn)
        return NULL;
139

140 141
    priv = (xenUnifiedPrivatePtr) conn->privateData;
    if (priv->xshandle == NULL)
142 143
        return (NULL);

144
    snprintf(s, 255, "/local/domain/%d/%s", domid, path);
145 146
    s[255] = 0;

147
    return xs_read(priv->xshandle, 0, &s[0], &len);
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
}

/**
 * virDomainDoStoreWrite:
 * @domain: a domain object
 * @path: the relative path of the data in the store to retrieve
 *
 * Internal API setting up a string value in the Xenstore
 * Requires write access to the XenStore
 *
 * Returns 0 in case of success, -1 in case of failure
 */
static int
virDomainDoStoreWrite(virDomainPtr domain, const char *path,
                      const char *value)
{
    char s[256];
165
    xenUnifiedPrivatePtr priv;
166 167 168 169
    int ret = -1;

    if (!VIR_IS_CONNECTED_DOMAIN(domain))
        return (-1);
170 171 172

    priv = (xenUnifiedPrivatePtr) domain->conn->privateData;
    if (priv->xshandle == NULL)
173 174 175 176
        return (-1);
    if (domain->conn->flags & VIR_CONNECT_RO)
        return (-1);

177
    snprintf(s, 255, "/local/domain/%d/%s", domain->id, path);
178 179
    s[255] = 0;

180
    if (xs_write(priv->xshandle, 0, &s[0], value, strlen(value)))
181 182 183 184 185 186 187 188 189 190 191 192 193
        ret = 0;

    return (ret);
}

/**
 * virDomainGetVM:
 * @domain: a domain object
 *
 * Internal API extracting a xenstore vm path.
 *
 * Returns the new string or NULL in case of error
 */
194
static char *
195 196 197 198 199
virDomainGetVM(virDomainPtr domain)
{
    char *vm;
    char query[200];
    unsigned int len;
200
    xenUnifiedPrivatePtr priv;
201 202 203

    if (!VIR_IS_CONNECTED_DOMAIN(domain))
        return (NULL);
204 205 206

    priv = (xenUnifiedPrivatePtr) domain->conn->privateData;
    if (priv->xshandle == NULL)
207 208 209 210 211
        return (NULL);

    snprintf(query, 199, "/local/domain/%d/vm", virDomainGetID(domain));
    query[199] = 0;

212
    vm = xs_read(priv->xshandle, 0, &query[0], &len);
213 214 215 216 217 218 219 220 221 222

    return (vm);
}

/**
 * virDomainGetVMInfo:
 * @domain: a domain object
 * @vm: the xenstore vm path
 * @name: the value's path
 *
223
 * Internal API extracting one information the device used
224 225 226 227
 * by the domain from xensttore
 *
 * Returns the new string or NULL in case of error
 */
228
static char *
229 230 231 232 233
virDomainGetVMInfo(virDomainPtr domain, const char *vm, const char *name)
{
    char s[256];
    char *ret = NULL;
    unsigned int len = 0;
234
    xenUnifiedPrivatePtr priv;
235 236 237

    if (!VIR_IS_CONNECTED_DOMAIN(domain))
        return (NULL);
238 239 240

    priv = (xenUnifiedPrivatePtr) domain->conn->privateData;
    if (priv->xshandle == NULL)
241 242 243 244 245
        return (NULL);

    snprintf(s, 255, "%s/%s", vm, name);
    s[255] = 0;

246
    ret = xs_read(priv->xshandle, 0, &s[0], &len);
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266

    return (ret);
}


/************************************************************************
 *									*
 *		Canonical internal APIs					*
 *									*
 ************************************************************************/
/**
 * xenStoreOpen:
 * @conn: pointer to the connection block
 * @name: URL for the target, NULL for local
 * @flags: combination of virDrvOpenFlag(s)
 *
 * Connects to the Xen hypervisor.
 *
 * Returns 0 or -1 in case of error.
 */
267
virDrvOpenStatus
268
xenStoreOpen(virConnectPtr conn,
269
             virConnectAuthPtr auth ATTRIBUTE_UNUSED,
270
             unsigned int flags ATTRIBUTE_UNUSED)
271
{
272
    xenUnifiedPrivatePtr priv = (xenUnifiedPrivatePtr) conn->privateData;
273

274
    if (flags & VIR_CONNECT_RO)
275
        priv->xshandle = xs_daemon_open_readonly();
276
    else
277
        priv->xshandle = xs_daemon_open();
278

279
    if (priv->xshandle == NULL) {
280
        /*
J
John Levon 已提交
281 282
         * not being able to connect via the socket as an unprivileged
         * user is rather normal, this should fallback to the proxy (or
283
         * remote) mechanism.
284
         */
J
John Levon 已提交
285
        if (xenHavePrivilege()) {
286 287
            virXenStoreError(VIR_ERR_NO_XEN,
                             "%s", _("failed to connect to Xen Store"));
288
        }
289 290
        return (-1);
    }
291 292

    /* Init activeDomainList */
293
    if (VIR_ALLOC(priv->activeDomainList) < 0) {
294
        virReportOOMError();
295 296 297 298 299 300
        return -1;
    }

    /* Init watch list before filling in domInfoList,
       so we can know if it is the first time through
       when the callback fires */
301
    if (VIR_ALLOC(priv->xsWatchList) < 0) {
302
        virReportOOMError();
303 304 305 306 307 308 309
        return -1;
    }

    /* This will get called once at start */
    if ( xenStoreAddWatch(conn, "@releaseDomain",
                     "releaseDomain", xenStoreDomainReleased, priv) < 0 )
    {
310 311
        virXenStoreError(VIR_ERR_INTERNAL_ERROR,
                         "%s", _("adding watch @releaseDomain"));
312 313 314 315 316 317 318
        return -1;
    }

    /* The initial call of this will fill domInfoList */
    if( xenStoreAddWatch(conn, "@introduceDomain",
                     "introduceDomain", xenStoreDomainIntroduced, priv) < 0 )
    {
319 320
        virXenStoreError(VIR_ERR_INTERNAL_ERROR,
                         "%s", _("adding watch @introduceDomain"));
321 322 323 324 325 326 327 328 329
        return -1;
    }

    /* Add an event handle */
    if ((priv->xsWatch = virEventAddHandle(xs_fileno(priv->xshandle),
                                           VIR_EVENT_HANDLE_READABLE,
                                           xenStoreWatchEvent,
                                           conn,
                                           NULL)) < 0)
330
        VIR_DEBUG("Failed to add event handle, disabling events");
331 332

    return 0;
333 334 335 336 337 338 339 340 341 342 343 344 345
}

/**
 * xenStoreClose:
 * @conn: pointer to the connection block
 *
 * Close the connection to the Xen hypervisor.
 *
 * Returns 0 in case of success or -1 in case of error.
 */
int
xenStoreClose(virConnectPtr conn)
{
346 347
    xenUnifiedPrivatePtr priv;

348
    if (conn == NULL) {
349
        virXenStoreError(VIR_ERR_INVALID_ARG, __FUNCTION__);
350
        return(-1);
351 352
    }

353
    priv = (xenUnifiedPrivatePtr) conn->privateData;
354 355

    if (xenStoreRemoveWatch(conn, "@introduceDomain", "introduceDomain") < 0) {
356
        VIR_DEBUG("Warning, could not remove @introduceDomain watch");
357 358 359 360
        /* not fatal */
    }

    if (xenStoreRemoveWatch(conn, "@releaseDomain", "releaseDomain") < 0) {
361
        VIR_DEBUG("Warning, could not remove @releaseDomain watch");
362 363 364 365
        /* not fatal */
    }

    xenStoreWatchListFree(priv->xsWatchList);
J
John Levon 已提交
366
    priv->xsWatchList = NULL;
367 368
    xenUnifiedDomainInfoListFree(priv->activeDomainList);
    priv->activeDomainList = NULL;
369

370 371 372
    if (priv->xshandle == NULL)
        return(-1);

373 374
    if (priv->xsWatch != -1)
        virEventRemoveHandle(priv->xsWatch);
375

376
    xs_daemon_close(priv->xshandle);
377 378
    priv->xshandle = NULL;

379 380 381 382 383 384
    return (0);
}

/**
 * xenStoreGetDomainInfo:
 * @domain: pointer to the domain block
385
 * @info: the place where information should be stored
386
 *
387
 * Do an hypervisor call to get the related set of domain information.
388 389 390 391 392 393 394 395 396
 *
 * Returns 0 in case of success, -1 in case of error.
 */
int
xenStoreGetDomainInfo(virDomainPtr domain, virDomainInfoPtr info)
{
    char *tmp, **tmp2;
    unsigned int nb_vcpus;
    char request[200];
397
    xenUnifiedPrivatePtr priv;
398

399 400 401
    if (!VIR_IS_CONNECTED_DOMAIN(domain))
        return (-1);

402
    if ((domain == NULL) || (domain->conn == NULL) || (info == NULL)) {
403
        virXenStoreError(VIR_ERR_INVALID_ARG, __FUNCTION__);
404
        return(-1);
405
    }
406 407 408

    priv = (xenUnifiedPrivatePtr) domain->conn->privateData;
    if (priv->xshandle == NULL)
409
        return(-1);
410

411
    if (domain->id == -1)
412
        return(-1);
413

414
    tmp = virDomainDoStoreQuery(domain->conn, domain->id, "running");
415 416 417
    if (tmp != NULL) {
        if (tmp[0] == '1')
            info->state = VIR_DOMAIN_RUNNING;
418
        VIR_FREE(tmp);
419
    } else {
420
        info->state = VIR_DOMAIN_NOSTATE;
421
    }
422
    tmp = virDomainDoStoreQuery(domain->conn, domain->id, "memory/target");
423 424 425
    if (tmp != NULL) {
        info->memory = atol(tmp);
        info->maxMem = atol(tmp);
426
        VIR_FREE(tmp);
427 428 429 430
    } else {
        info->memory = 0;
        info->maxMem = 0;
    }
431
#if 0
432
    /* doesn't seems to work */
433
    tmp = virDomainDoStoreQuery(domain->conn, domain->id, "cpu_time");
434 435
    if (tmp != NULL) {
        info->cpuTime = atol(tmp);
436
        VIR_FREE(tmp);
437 438 439
    } else {
        info->cpuTime = 0;
    }
440
#endif
441
    snprintf(request, 199, "/local/domain/%d/cpu", domain->id);
442 443 444 445
    request[199] = 0;
    tmp2 = virConnectDoStoreList(domain->conn, request, &nb_vcpus);
    if (tmp2 != NULL) {
        info->nrVirtCpu = nb_vcpus;
446
        VIR_FREE(tmp2);
447 448 449 450
    }
    return (0);
}

451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
/**
 * xenStoreDomainGetState:
 * @domain: pointer to the domain block
 * @state: returned domain's state
 * @reason: returned state reason
 * @flags: additional flags, 0 for now
 *
 * Returns 0 in case of success, -1 in case of error.
 */
int
xenStoreDomainGetState(virDomainPtr domain,
                       int *state,
                       int *reason,
                       unsigned int flags ATTRIBUTE_UNUSED)
{
    char *running;

    if (domain->id == -1)
        return -1;

    running = virDomainDoStoreQuery(domain->conn, domain->id, "running");

    if (running && *running == '1')
        *state = VIR_DOMAIN_RUNNING;
    else
        *state = VIR_DOMAIN_NOSTATE;
    if (reason)
        *reason = 0;

    VIR_FREE(running);

    return 0;
}

485
/**
486
 * xenStoreDomainSetMemory:
487 488 489 490 491 492 493 494
 * @domain: pointer to the domain block
 * @memory: the max memory size in kilobytes.
 *
 * Change the maximum amount of memory allowed in the xen store
 *
 * Returns 0 in case of success, -1 in case of error.
 */
int
495
xenStoreDomainSetMemory(virDomainPtr domain, unsigned long memory)
496 497 498 499
{
    int ret;
    char value[20];

D
Daniel Veillard 已提交
500 501
    if ((domain == NULL) || (domain->conn == NULL) ||
        (memory < 1024 * MIN_XEN_GUEST_SIZE)) {
502
        virXenStoreError(VIR_ERR_INVALID_ARG, __FUNCTION__);
503
        return(-1);
504
    }
505
    if (domain->id == -1)
506
        return(-1);
D
Daniel Veillard 已提交
507
    if ((domain->id == 0) && (memory < (2 * MIN_XEN_GUEST_SIZE * 1024)))
508
        return(-1);
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
    snprintf(value, 19, "%lu", memory);
    value[19] = 0;
    ret = virDomainDoStoreWrite(domain, "memory/target", &value[0]);
    if (ret < 0)
        return (-1);
    return (0);
}

/**
 * xenStoreDomainGetMaxMemory:
 * @domain: pointer to the domain block
 *
 * Ask the xenstore for the maximum memory allowed for a domain
 *
 * Returns the memory size in kilobytes or 0 in case of error.
 */
unsigned long
xenStoreDomainGetMaxMemory(virDomainPtr domain)
{
    char *tmp;
    unsigned long ret = 0;
D
Daniel P. Berrange 已提交
530
    xenUnifiedPrivatePtr priv;
531

532 533
    if (!VIR_IS_CONNECTED_DOMAIN(domain))
        return (ret);
534
    if (domain->id == -1)
535
        return(-1);
536

D
Daniel P. Berrange 已提交
537 538
    priv = domain->conn->privateData;
    xenUnifiedLock(priv);
539
    tmp = virDomainDoStoreQuery(domain->conn, domain->id, "memory/target");
540
    if (tmp != NULL) {
541
        ret = (unsigned long) atol(tmp);
D
Daniel P. Berrange 已提交
542
        VIR_FREE(tmp);
543
    }
D
Daniel P. Berrange 已提交
544
    xenUnifiedUnlock(priv);
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
    return(ret);
}

/**
 * xenStoreNumOfDomains:
 * @conn: pointer to the hypervisor connection
 *
 * Provides the number of active domains.
 *
 * Returns the number of domain found or -1 in case of error
 */
int
xenStoreNumOfDomains(virConnectPtr conn)
{
    unsigned int num;
560 561 562
    char **idlist = NULL, *endptr;
    int i, ret = -1, realnum = 0;
    long id;
563
    xenUnifiedPrivatePtr priv;
564

565
    if (conn == NULL) {
566
        virXenStoreError(VIR_ERR_INVALID_ARG, __FUNCTION__);
567
        return -1;
568
    }
569 570 571

    priv = (xenUnifiedPrivatePtr) conn->privateData;
    if (priv->xshandle == NULL) {
572
        virXenStoreError(VIR_ERR_INVALID_ARG, __FUNCTION__);
573 574
        return(-1);
    }
575

576
    idlist = xs_directory(priv->xshandle, 0, "/local/domain", &num);
577
    if (idlist) {
578 579 580 581 582 583 584 585 586 587 588 589 590
        for (i = 0; i < num; i++) {
            id = strtol(idlist[i], &endptr, 10);
            if ((endptr == idlist[i]) || (*endptr != 0))
                goto out;

            /* Sometimes xenstore has stale domain IDs, so filter
               against the hypervisor's info */
            if (xenHypervisorHasDomain(conn, (int)id))
                realnum++;
        }
out:
        VIR_FREE (idlist);
        ret = realnum;
591 592 593 594 595
    }
    return(ret);
}

/**
596
 * xenStoreDoListDomains:
597 598 599 600
 * @conn: pointer to the hypervisor connection
 * @ids: array to collect the list of IDs of active domains
 * @maxids: size of @ids
 *
601 602
 * Internal API: collect the list of active domains, and store
 * their ID in @maxids. The driver lock must be held.
603 604 605
 *
 * Returns the number of domain found or -1 in case of error
 */
606
static int
607
xenStoreDoListDomains(virConnectPtr conn, xenUnifiedPrivatePtr priv, int *ids, int maxids)
608 609 610
{
    char **idlist = NULL, *endptr;
    unsigned int num, i;
611
    int ret = -1;
612
    long id;
D
Daniel P. Berrange 已提交
613

614
    if (priv->xshandle == NULL)
615
        goto out;
616

617
    idlist = xs_directory (priv->xshandle, 0, "/local/domain", &num);
618
    if (idlist == NULL)
619
        goto out;
620 621

    for (ret = 0, i = 0; (i < num) && (ret < maxids); i++) {
622
        id = strtol(idlist[i], &endptr, 10);
623 624
        if ((endptr == idlist[i]) || (*endptr != 0))
            goto out;
625 626 627 628 629

        /* Sometimes xenstore has stale domain IDs, so filter
           against the hypervisor's info */
        if (xenHypervisorHasDomain(conn, (int)id))
            ids[ret++] = (int) id;
630
    }
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653

out:
    VIR_FREE (idlist);
    return ret;
}

/**
 * xenStoreListDomains:
 * @conn: pointer to the hypervisor connection
 * @ids: array to collect the list of IDs of active domains
 * @maxids: size of @ids
 *
 * Collect the list of active domains, and store their ID in @maxids
 *
 * Returns the number of domain found or -1 in case of error
 */
int
xenStoreListDomains(virConnectPtr conn, int *ids, int maxids)
{
    xenUnifiedPrivatePtr priv;
    int ret;

    if ((conn == NULL) || (ids == NULL)) {
654
        virXenStoreError(VIR_ERR_INVALID_ARG, __FUNCTION__);
655 656 657 658 659 660
        return(-1);
    }

    priv = (xenUnifiedPrivatePtr) conn->privateData;

    xenUnifiedLock(priv);
661
    ret = xenStoreDoListDomains(conn, priv, ids, maxids);
D
Daniel P. Berrange 已提交
662
    xenUnifiedUnlock(priv);
663 664

    return(ret);
665 666 667
}

/**
668
 * xenStoreLookupByName:
669 670 671 672 673 674 675 676
 * @conn: A xend instance
 * @name: The name of the domain
 *
 * Try to lookup a domain on the Xen Store based on its name.
 *
 * Returns a new domain object or NULL in case of failure
 */
virDomainPtr
677
xenStoreLookupByName(virConnectPtr conn, const char *name)
678 679 680 681 682
{
    virDomainPtr ret = NULL;
    unsigned int num, i, len;
    long id = -1;
    char **idlist = NULL, *endptr;
683
    char prop[200], *tmp;
684 685
    int found = 0;
    struct xend_domain *xenddomain = NULL;
686
    xenUnifiedPrivatePtr priv;
687 688

    if ((conn == NULL) || (name == NULL)) {
689
        virXenStoreError(VIR_ERR_INVALID_ARG, __FUNCTION__);
690
        return(NULL);
691
    }
692 693 694

    priv = (xenUnifiedPrivatePtr) conn->privateData;
    if (priv->xshandle == NULL)
695 696
        return(NULL);

697
    idlist = xs_directory(priv->xshandle, 0, "/local/domain", &num);
698
    if (idlist == NULL)
699
        goto done;
700 701

    for (i = 0; i < num; i++) {
702 703 704 705
        id = strtol(idlist[i], &endptr, 10);
        if ((endptr == idlist[i]) || (*endptr != 0)) {
            goto done;
        }
706
#if 0
707 708
        if (virConnectCheckStoreID(conn, (int) id) < 0)
            continue;
709
#endif
710 711 712 713 714
        snprintf(prop, 199, "/local/domain/%s/name", idlist[i]);
        prop[199] = 0;
        tmp = xs_read(priv->xshandle, 0, prop, &len);
        if (tmp != NULL) {
            found = STREQ (name, tmp);
715
            VIR_FREE(tmp);
716 717 718
            if (found)
                break;
        }
719 720
    }
    if (!found)
721
        goto done;
722

723
    ret = virGetDomain(conn, name, NULL);
724
    if (ret == NULL)
725
        goto done;
726

727
    ret->id = id;
728 729

done:
730 731
    VIR_FREE(xenddomain);
    VIR_FREE(idlist);
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748

    return(ret);
}

/**
 * xenStoreDomainShutdown:
 * @domain: pointer to the Domain block
 *
 * Shutdown the domain, the OS is requested to properly shutdown
 * and the domain may ignore it.  It will return immediately
 * after queuing the request.
 *
 * Returns 0 in case of success, -1 in case of error.
 */
int
xenStoreDomainShutdown(virDomainPtr domain)
{
D
Daniel P. Berrange 已提交
749 750 751
    int ret;
    xenUnifiedPrivatePtr priv;

752
    if ((domain == NULL) || (domain->conn == NULL)) {
753
        virXenStoreError(VIR_ERR_INVALID_ARG, __FUNCTION__);
754 755
        return(-1);
    }
756
    if (domain->id == -1 || domain->id == 0)
757
        return(-1);
758
    /*
759
     * this is very hackish, the domU kernel probes for a special
760 761
     * node in the xenstore and launch the shutdown command if found.
     */
D
Daniel P. Berrange 已提交
762 763 764 765 766
    priv = domain->conn->privateData;
    xenUnifiedLock(priv);
    ret = virDomainDoStoreWrite(domain, "control/shutdown", "poweroff");
    xenUnifiedUnlock(priv);
    return ret;
767 768
}

769 770 771 772 773 774 775 776 777 778 779 780 781 782
/**
 * xenStoreDomainReboot:
 * @domain: pointer to the Domain block
 * @flags: extra flags for the reboot operation, not used yet
 *
 * Reboot the domain, the OS is requested to properly shutdown
 * and reboot but the domain may ignore it.  It will return immediately
 * after queuing the request.
 *
 * Returns 0 in case of success, -1 in case of error.
 */
int
xenStoreDomainReboot(virDomainPtr domain, unsigned int flags ATTRIBUTE_UNUSED)
{
D
Daniel P. Berrange 已提交
783 784 785
    int ret;
    xenUnifiedPrivatePtr priv;

786
    if ((domain == NULL) || (domain->conn == NULL)) {
787
        virXenStoreError(VIR_ERR_INVALID_ARG, __FUNCTION__);
788 789
        return(-1);
    }
790
    if (domain->id == -1 || domain->id == 0)
791
        return(-1);
792
    /*
793
     * this is very hackish, the domU kernel probes for a special
794 795
     * node in the xenstore and launch the shutdown command if found.
     */
D
Daniel P. Berrange 已提交
796 797 798 799 800
    priv = domain->conn->privateData;
    xenUnifiedLock(priv);
    ret = virDomainDoStoreWrite(domain, "control/shutdown", "reboot");
    xenUnifiedUnlock(priv);
    return ret;
801
}
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816

/*
 * xenStoreDomainGetOSType:
 * @domain: a domain object
 *
 * Get the type of domain operation system.
 *
 * Returns the new string or NULL in case of error, the string must be
 *         freed by the caller.
 */
static char *
xenStoreDomainGetOSType(virDomainPtr domain) {
    char *vm, *str = NULL;

    if ((domain == NULL) || (domain->conn == NULL)) {
817
        virXenStoreError(VIR_ERR_INVALID_ARG, __FUNCTION__);
818 819 820 821 822
        return(NULL);
    }

    vm = virDomainGetVM(domain);
    if (vm) {
D
Daniel P. Berrange 已提交
823 824
        xenUnifiedPrivatePtr priv = domain->conn->privateData;
        xenUnifiedLock(priv);
825
        str = virDomainGetVMInfo(domain, vm, "image/ostype");
D
Daniel P. Berrange 已提交
826 827
        xenUnifiedUnlock(priv);
        VIR_FREE(vm);
828 829 830 831
    }

    return (str);
}
832

833 834
/**
 * xenStoreDomainGetVNCPort:
835 836
 * @conn: the hypervisor connection
 * @domid: id of the domain
837 838
 *
 * Return the port number on which the domain is listening for VNC
839
 * connections.
840
 *
D
Daniel P. Berrange 已提交
841 842 843
 * The caller must hold the lock on the privateData
 * associated with the 'conn' parameter.
 *
844 845
 * Returns the port number, -1 in case of error
 */
846
int             xenStoreDomainGetVNCPort(virConnectPtr conn, int domid) {
847 848 849
    char *tmp;
    int ret = -1;

850
    tmp = virDomainDoStoreQuery(conn, domid, "console/vnc-port");
851 852 853 854 855
    if (tmp != NULL) {
        char *end;
        ret = strtol(tmp, &end, 10);
        if (ret == 0 && end == tmp)
            ret = -1;
856
        VIR_FREE(tmp);
857 858 859 860 861 862
    }
    return(ret);
}

/**
 * xenStoreDomainGetConsolePath:
863 864
 * @conn: the hypervisor connection
 * @domid: id of the domain
865
 *
866
 * Return the path to the pseudo TTY on which the guest domain's
867 868 869 870 871
 * serial console is attached.
 *
 * Returns the path to the serial console. It is the callers
 * responsibilty to free() the return string. Returns NULL
 * on error
D
Daniel P. Berrange 已提交
872 873 874
 *
 * The caller must hold the lock on the privateData
 * associated with the 'conn' parameter.
875
 */
876 877
char *          xenStoreDomainGetConsolePath(virConnectPtr conn, int domid) {
  return virDomainDoStoreQuery(conn, domid, "console/tty");
878
}
879

880 881 882 883 884 885 886 887 888 889

/*
 * xenStoreDomainGetNetworkID:
 * @conn: pointer to the connection.
 * @id: the domain id
 * @mac: the mac address
 *
 * Get the reference (i.e. the string number) for the device on that domain
 * which uses the given mac address
 *
D
Daniel P. Berrange 已提交
890 891 892
 * The caller must hold the lock on the privateData
 * associated with the 'conn' parameter.
 *
893 894 895 896 897 898
 * Returns the new string or NULL in case of error, the string must be
 *         freed by the caller.
 */
char *
xenStoreDomainGetNetworkID(virConnectPtr conn, int id, const char *mac) {
    char dir[80], path[128], **list = NULL, *val = NULL;
899
    unsigned int len, i, num;
900
    char *ret = NULL;
901
    xenUnifiedPrivatePtr priv;
902 903 904

    if (id < 0)
        return(NULL);
905 906 907

    priv = (xenUnifiedPrivatePtr) conn->privateData;
    if (priv->xshandle == NULL)
908 909 910 911
        return (NULL);
    if (mac == NULL)
        return (NULL);

912
    snprintf(dir, sizeof(dir), "/local/domain/0/backend/vif/%d", id);
913
    list = xs_directory(priv->xshandle, 0, dir, &num);
914
    if (list == NULL)
915
        return(NULL);
916
    for (i = 0; i < num; i++) {
917
        snprintf(path, sizeof(path), "%s/%s/%s", dir, list[i], "mac");
918
        if ((val = xs_read(priv->xshandle, 0, path, &len)) == NULL)
919
            break;
920 921 922 923 924 925

        bool match = (virMacAddrCompare(val, mac) == 0);

        VIR_FREE(val);

        if (match) {
926
            ret = strdup(list[i]);
927 928

            if (ret == NULL)
929
                virReportOOMError();
930

931 932
            break;
        }
933
    }
934 935

    VIR_FREE(list);
936 937
    return(ret);
}
938

939 940 941 942 943 944 945 946 947
/*
 * xenStoreDomainGetDiskID:
 * @conn: pointer to the connection.
 * @id: the domain id
 * @dev: the virtual block device name
 *
 * Get the reference (i.e. the string number) for the device on that domain
 * which uses the given virtual block device name
 *
D
Daniel P. Berrange 已提交
948 949 950
 * The caller must hold the lock on the privateData
 * associated with the 'conn' parameter.
 *
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
 * Returns the new string or NULL in case of error, the string must be
 *         freed by the caller.
 */
char *
xenStoreDomainGetDiskID(virConnectPtr conn, int id, const char *dev) {
    char dir[80], path[128], **list = NULL, *val = NULL;
    unsigned int devlen, len, i, num;
    char *ret = NULL;
    xenUnifiedPrivatePtr priv;

    if (id < 0)
        return(NULL);

    priv = (xenUnifiedPrivatePtr) conn->privateData;
    if (priv->xshandle == NULL)
        return (NULL);
    if (dev == NULL)
        return (NULL);
    devlen = strlen(dev);
    if (devlen <= 0)
        return (NULL);

    snprintf(dir, sizeof(dir), "/local/domain/0/backend/vbd/%d", id);
    list = xs_directory(priv->xshandle, 0, dir, &num);
975 976 977 978 979 980 981
    if (list != NULL) {
        for (i = 0; i < num; i++) {
            snprintf(path, sizeof(path), "%s/%s/%s", dir, list[i], "dev");
            val = xs_read(priv->xshandle, 0, path, &len);
            if (val == NULL)
                break;
            if ((devlen != len) || memcmp(val, dev, len)) {
982
                VIR_FREE (val);
983 984
            } else {
                ret = strdup(list[i]);
985 986

                if (ret == NULL)
987
                    virReportOOMError();
988 989 990

                VIR_FREE (val);
                VIR_FREE (list);
991 992
                return (ret);
            }
993
        }
994
        VIR_FREE (list);
995
    }
996 997 998 999 1000 1001 1002 1003 1004
    snprintf(dir, sizeof(dir), "/local/domain/0/backend/tap/%d", id);
    list = xs_directory(priv->xshandle, 0, dir, &num);
    if (list != NULL) {
        for (i = 0; i < num; i++) {
            snprintf(path, sizeof(path), "%s/%s/%s", dir, list[i], "dev");
            val = xs_read(priv->xshandle, 0, path, &len);
            if (val == NULL)
                break;
            if ((devlen != len) || memcmp(val, dev, len)) {
1005
                VIR_FREE (val);
1006 1007
            } else {
                ret = strdup(list[i]);
1008 1009

                if (ret == NULL)
1010
                    virReportOOMError();
1011 1012 1013

                VIR_FREE (val);
                VIR_FREE (list);
1014 1015 1016
                return (ret);
            }
        }
1017
        VIR_FREE (list);
1018 1019
    }
    return (NULL);
1020 1021
}

1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
/*
 * xenStoreDomainGetPCIID:
 * @conn: pointer to the connection.
 * @id: the domain id
 * @bdf: the PCI BDF
 *
 * Get the reference (i.e. the string number) for the device on that domain
 * which uses the given PCI address
 *
 * The caller must hold the lock on the privateData
 * associated with the 'conn' parameter.
 *
 * Returns the new string or NULL in case of error, the string must be
 *         freed by the caller.
 */
char *
xenStoreDomainGetPCIID(virConnectPtr conn, int id, const char *bdf)
{
    char dir[80], path[128], **list = NULL, *val = NULL;
    unsigned int len, i, num;
    char *ret = NULL;
    xenUnifiedPrivatePtr priv;

    if (id < 0)
        return(NULL);

    priv = (xenUnifiedPrivatePtr) conn->privateData;
    if (priv->xshandle == NULL)
        return (NULL);
    if (bdf == NULL)
        return (NULL);

    snprintf(dir, sizeof(dir), "/local/domain/0/backend/pci/%d", id);
    list = xs_directory(priv->xshandle, 0, dir, &num);
    if (list == NULL)
        return(NULL);
    for (i = 0; i < num; i++) {
        snprintf(path, sizeof(path), "%s/%s/%s", dir, list[i], "dev-0");
        if ((val = xs_read(priv->xshandle, 0, path, &len)) == NULL)
            break;

        bool match = STREQ(val, bdf);

        VIR_FREE(val);

        if (match) {
            ret = strdup(list[i]);
            break;
        }
    }

    VIR_FREE(list);
    return(ret);
}

D
Daniel P. Berrange 已提交
1077 1078 1079 1080
/*
 * The caller must hold the lock on the privateData
 * associated with the 'conn' parameter.
 */
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
char *xenStoreDomainGetName(virConnectPtr conn,
                            int id) {
    char prop[200];
    xenUnifiedPrivatePtr priv;
    unsigned int len;

    priv = (xenUnifiedPrivatePtr) conn->privateData;
    if (priv->xshandle == NULL)
        return(NULL);

    snprintf(prop, 199, "/local/domain/%d/name", id);
    prop[199] = 0;
    return xs_read(priv->xshandle, 0, prop, &len);
}

D
Daniel P. Berrange 已提交
1096 1097 1098 1099
/*
 * The caller must hold the lock on the privateData
 * associated with the 'conn' parameter.
 */
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
int xenStoreDomainGetUUID(virConnectPtr conn,
                          int id,
                          unsigned char *uuid) {
    char prop[200];
    xenUnifiedPrivatePtr priv;
    unsigned int len;
    char *uuidstr;
    int ret = 0;

    priv = (xenUnifiedPrivatePtr) conn->privateData;
    if (priv->xshandle == NULL)
        return -1;

    snprintf(prop, 199, "/local/domain/%d/vm", id);
    prop[199] = 0;
1115 1116
    /* This will return something like
     * /vm/00000000-0000-0000-0000-000000000000 */
1117 1118
    uuidstr = xs_read(priv->xshandle, 0, prop, &len);

1119
    /* remove "/vm/" */
1120 1121 1122 1123 1124 1125 1126
    ret = virUUIDParse(uuidstr + 4, uuid);

    VIR_FREE(uuidstr);

    return ret;
}

D
Daniel P. Berrange 已提交
1127 1128
static void
xenStoreWatchListFree(xenStoreWatchListPtr list)
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
{
    int i;
    for (i=0; i<list->count; i++) {
        VIR_FREE(list->watches[i]->path);
        VIR_FREE(list->watches[i]->token);
        VIR_FREE(list->watches[i]);
    }
    VIR_FREE(list);
}

D
Daniel P. Berrange 已提交
1139 1140 1141 1142
/*
 * The caller must hold the lock on the privateData
 * associated with the 'conn' parameter.
 */
1143 1144 1145 1146 1147 1148
int xenStoreAddWatch(virConnectPtr conn,
                     const char *path,
                     const char *token,
                     xenStoreWatchCallback cb,
                     void *opaque)
{
1149
    xenStoreWatchPtr watch = NULL;
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
    int n;
    xenStoreWatchListPtr list;
    xenUnifiedPrivatePtr priv = (xenUnifiedPrivatePtr) conn->privateData;

    if (priv->xshandle == NULL)
        return -1;

    list = priv->xsWatchList;
    if(!list)
        return -1;

    /* check if we already have this callback on our list */
    for (n=0; n < list->count; n++) {
        if( STREQ(list->watches[n]->path, path) &&
            STREQ(list->watches[n]->token, token)) {
1165 1166
            virXenStoreError(VIR_ERR_INTERNAL_ERROR,
                             "%s", _("watch already tracked"));
1167 1168 1169 1170 1171
            return -1;
        }
    }

    if (VIR_ALLOC(watch) < 0)
1172 1173
        goto no_memory;

1174 1175 1176 1177 1178
    watch->path   = strdup(path);
    watch->token  = strdup(token);
    watch->cb     = cb;
    watch->opaque = opaque;

1179 1180 1181 1182
    if (watch->path == NULL || watch->token == NULL) {
        goto no_memory;
    }

1183 1184 1185
    /* Make space on list */
    n = list->count;
    if (VIR_REALLOC_N(list->watches, n + 1) < 0) {
1186
        goto no_memory;
1187 1188 1189 1190 1191 1192
    }

    list->watches[n] = watch;
    list->count++;

    return xs_watch(priv->xshandle, watch->path, watch->token);
1193 1194 1195 1196 1197 1198 1199 1200

  no_memory:
    if (watch) {
        VIR_FREE(watch->path);
        VIR_FREE(watch->token);
        VIR_FREE(watch);
    }

1201
    virReportOOMError();
1202 1203

    return -1;
1204 1205
}

D
Daniel P. Berrange 已提交
1206 1207 1208 1209
/*
 * The caller must hold the lock on the privateData
 * associated with the 'conn' parameter.
 */
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
int xenStoreRemoveWatch(virConnectPtr conn,
                        const char *path,
                        const char *token)
{
    int i;
    xenStoreWatchListPtr list;
    xenUnifiedPrivatePtr priv = (xenUnifiedPrivatePtr) conn->privateData;

    if (priv->xshandle == NULL)
        return -1;

    list = priv->xsWatchList;
    if(!list)
        return -1;

    for (i = 0 ; i < list->count ; i++) {
        if( STREQ(list->watches[i]->path, path) &&
            STREQ(list->watches[i]->token, token)) {

            if (!xs_unwatch(priv->xshandle,
                       list->watches[i]->path,
1231
                       list->watches[i]->token))
1232
            {
1233
                VIR_DEBUG("WARNING: Could not remove watch");
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
                /* Not fatal, continue */
            }

            VIR_FREE(list->watches[i]->path);
            VIR_FREE(list->watches[i]->token);
            VIR_FREE(list->watches[i]);

            if (i < (list->count - 1))
                memmove(list->watches + i,
                        list->watches + i + 1,
                        sizeof(*(list->watches)) *
                                (list->count - (i + 1)));

            if (VIR_REALLOC_N(list->watches,
                              list->count - 1) < 0) {
                ; /* Failure to reduce memory allocation isn't fatal */
            }
            list->count--;
            return 0;
        }
    }
    return -1;
}

D
Daniel P. Berrange 已提交
1258 1259 1260 1261
static xenStoreWatchPtr
xenStoreFindWatch(xenStoreWatchListPtr list,
                  const char *path,
                  const char *token)
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
{
    int i;
    for (i = 0 ; i < list->count ; i++)
        if( STREQ(path, list->watches[i]->path) &&
            STREQ(token, list->watches[i]->token) )
            return list->watches[i];

    return NULL;
}

D
Daniel P. Berrange 已提交
1272 1273 1274
static void
xenStoreWatchEvent(int watch ATTRIBUTE_UNUSED,
                   int fd ATTRIBUTE_UNUSED,
1275
                   int events,
D
Daniel P. Berrange 已提交
1276
                   void *data)
1277 1278 1279 1280 1281 1282 1283 1284 1285
{
    char		 **event;
    char		 *path;
    char		 *token;
    unsigned int	 stringCount;
    xenStoreWatchPtr     sw;

    virConnectPtr        conn = data;
    xenUnifiedPrivatePtr priv = (xenUnifiedPrivatePtr) conn->privateData;
1286

1287
    if(!priv) return;
D
Daniel P. Berrange 已提交
1288

1289 1290 1291
    /* only set a watch on read and write events */
    if (events & (VIR_EVENT_HANDLE_ERROR | VIR_EVENT_HANDLE_HANGUP)) return;

D
Daniel P. Berrange 已提交
1292 1293 1294 1295
    xenUnifiedLock(priv);

    if(!priv->xshandle)
        goto cleanup;
1296 1297 1298

    event = xs_read_watch(priv->xshandle, &stringCount);
    if (!event)
D
Daniel P. Berrange 已提交
1299
        goto cleanup;
1300 1301 1302 1303 1304 1305 1306 1307

    path  = event[XS_WATCH_PATH];
    token = event[XS_WATCH_TOKEN];

    sw = xenStoreFindWatch(priv->xsWatchList, path, token);
    if( sw )
        sw->cb(conn, path, token, sw->opaque);
    VIR_FREE(event);
D
Daniel P. Berrange 已提交
1308 1309 1310

cleanup:
    xenUnifiedUnlock(priv);
1311 1312
}

D
Daniel P. Berrange 已提交
1313 1314 1315 1316 1317 1318

/*
 * The domain callback for the @introduceDomain watch
 *
 * The lock on 'priv' is held when calling this
 */
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
int xenStoreDomainIntroduced(virConnectPtr conn,
                             const char *path ATTRIBUTE_UNUSED,
                             const char *token ATTRIBUTE_UNUSED,
                             void *opaque)
{
    int i, j, found, missing = 0, retries = 20;
    int new_domain_cnt;
    int *new_domids;
    int nread;

1329
    xenUnifiedPrivatePtr priv = opaque;
1330 1331 1332

retry:
    new_domain_cnt = xenStoreNumOfDomains(conn);
1333 1334 1335
    if (new_domain_cnt < 0)
        return -1;

1336
    if( VIR_ALLOC_N(new_domids,new_domain_cnt) < 0 ) {
1337
        virReportOOMError();
1338 1339
        return -1;
    }
1340
    nread = xenStoreDoListDomains(conn, priv, new_domids, new_domain_cnt);
1341
    if (nread != new_domain_cnt) {
1342
        /* mismatch. retry this read */
1343 1344 1345 1346 1347 1348 1349
        VIR_FREE(new_domids);
        goto retry;
    }

    missing = 0;
    for (i=0 ; i < new_domain_cnt ; i++) {
        found = 0;
1350 1351
        for (j = 0 ; j < priv->activeDomainList->count ; j++) {
            if (priv->activeDomainList->doms[j]->id == new_domids[i]) {
1352 1353 1354 1355 1356 1357
                found = 1;
                break;
            }
        }

        if (!found) {
1358
            virDomainEventPtr event;
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
            char *name;
            unsigned char uuid[VIR_UUID_BUFLEN];

            if (!(name = xenStoreDomainGetName(conn, new_domids[i]))) {
                missing = 1;
                continue;
            }
            if (xenStoreDomainGetUUID(conn, new_domids[i], uuid) < 0) {
                missing = 1;
                VIR_FREE(name);
                continue;
            }

1372 1373 1374 1375 1376
            event = virDomainEventNew(new_domids[i], name, uuid,
                                      VIR_DOMAIN_EVENT_STARTED,
                                      VIR_DOMAIN_EVENT_STARTED_BOOTED);
            if (event)
                xenUnifiedDomainEventDispatch(priv, event);
1377

1378
            /* Add to the list */
1379
            xenUnifiedAddDomainInfo(priv->activeDomainList,
1380
                                    new_domids[i], name, uuid);
1381 1382 1383 1384 1385 1386 1387

            VIR_FREE(name);
        }
    }
    VIR_FREE(new_domids);

    if (missing && retries--) {
1388
        VIR_DEBUG("Some domains were missing, trying again");
1389 1390 1391 1392 1393 1394
        usleep(100 * 1000);
        goto retry;
    }
    return 0;
}

D
Daniel P. Berrange 已提交
1395 1396 1397 1398 1399
/*
 * The domain callback for the @destroyDomain watch
 *
 * The lock on 'priv' is held when calling this
 */
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
int xenStoreDomainReleased(virConnectPtr conn,
                            const char *path  ATTRIBUTE_UNUSED,
                            const char *token ATTRIBUTE_UNUSED,
                            void *opaque)
{
    int i, j, found, removed, retries = 20;
    int new_domain_cnt;
    int *new_domids;
    int nread;

    xenUnifiedPrivatePtr priv = (xenUnifiedPrivatePtr) opaque;

1412
    if(!priv->activeDomainList->count) return 0;
1413 1414 1415

retry:
    new_domain_cnt = xenStoreNumOfDomains(conn);
1416 1417
    if (new_domain_cnt < 0)
        return -1;
1418 1419

    if( VIR_ALLOC_N(new_domids,new_domain_cnt) < 0 ) {
1420
        virReportOOMError();
1421 1422
        return -1;
    }
1423
    nread = xenStoreDoListDomains(conn, priv, new_domids, new_domain_cnt);
1424
    if (nread != new_domain_cnt) {
1425
        /* mismatch. retry this read */
1426 1427 1428 1429 1430
        VIR_FREE(new_domids);
        goto retry;
    }

    removed = 0;
1431
    for (j=0 ; j < priv->activeDomainList->count ; j++) {
1432 1433
        found = 0;
        for (i=0 ; i < new_domain_cnt ; i++) {
1434
            if (priv->activeDomainList->doms[j]->id == new_domids[i]) {
1435 1436 1437 1438 1439 1440
                found = 1;
                break;
            }
        }

        if (!found) {
1441 1442
            virDomainEventPtr event =
                virDomainEventNew(-1,
1443 1444
                                  priv->activeDomainList->doms[j]->name,
                                  priv->activeDomainList->doms[j]->uuid,
1445 1446 1447 1448 1449 1450
                                  VIR_DOMAIN_EVENT_STOPPED,
                                  VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN);
            if (event)
                xenUnifiedDomainEventDispatch(priv, event);

            /* Remove from the list */
1451 1452 1453 1454
            xenUnifiedRemoveDomainInfo(priv->activeDomainList,
                                       priv->activeDomainList->doms[j]->id,
                                       priv->activeDomainList->doms[j]->name,
                                       priv->activeDomainList->doms[j]->uuid);
1455 1456

            removed = 1;
1457 1458 1459 1460 1461 1462
        }
    }

    VIR_FREE(new_domids);

    if (!removed && retries--) {
1463
        VIR_DEBUG("No domains removed, retrying");
1464 1465 1466 1467 1468
        usleep(100 * 1000);
        goto retry;
    }
    return 0;
}