uml_driver.c 72.1 KB
Newer Older
1 2 3
/*
 * uml_driver.c: core driver methods for managing UML guests
 *
4
 * Copyright (C) 2006-2012 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2006-2008 Daniel P. Berrange
 *
 * 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
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#include <sys/types.h>
#include <sys/poll.h>
#include <limits.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/utsname.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <paths.h>
#include <pwd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <sys/inotify.h>
45
#include <sys/un.h>
46 47 48 49 50 51 52 53 54 55 56

#include "uml_driver.h"
#include "uml_conf.h"
#include "buf.h"
#include "util.h"
#include "nodeinfo.h"
#include "stats_linux.h"
#include "capabilities.h"
#include "memory.h"
#include "uuid.h"
#include "domain_conf.h"
57
#include "domain_audit.h"
58
#include "datatypes.h"
59
#include "logging.h"
60
#include "domain_nwfilter.h"
E
Eric Blake 已提交
61
#include "virfile.h"
62
#include "fdstream.h"
63
#include "configmake.h"
64
#include "virnetdevtap.h"
65
#include "virnodesuspend.h"
M
Martin Kletzander 已提交
66
#include "viruri.h"
67

68 69
#define VIR_FROM_THIS VIR_FROM_UML

70
/* For storing short-lived temporary files. */
71
#define TEMPDIR LOCALSTATEDIR "/cache/libvirt"
72

73 74 75 76 77 78 79
typedef struct _umlDomainObjPrivate umlDomainObjPrivate;
typedef umlDomainObjPrivate *umlDomainObjPrivatePtr;
struct _umlDomainObjPrivate {
    int monitor;
    int monitorWatch;
};

80 81 82 83 84 85 86 87 88 89
static int umlProcessAutoDestroyInit(struct uml_driver *driver);
static void umlProcessAutoDestroyRun(struct uml_driver *driver,
                                     virConnectPtr conn);
static void umlProcessAutoDestroyShutdown(struct uml_driver *driver);
static int umlProcessAutoDestroyAdd(struct uml_driver *driver,
                                    virDomainObjPtr vm,
                                    virConnectPtr conn);
static int umlProcessAutoDestroyRemove(struct uml_driver *driver,
                                       virDomainObjPtr vm);

90

91 92
static int umlShutdown(void);

93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
static void *umlDomainObjPrivateAlloc(void)
{
    umlDomainObjPrivatePtr priv;

    if (VIR_ALLOC(priv) < 0)
        return NULL;

    priv->monitor = -1;
    priv->monitorWatch = -1;

    return priv;
}

static void umlDomainObjPrivateFree(void *data)
{
    umlDomainObjPrivatePtr priv = data;

    VIR_FREE(priv);
}


114 115
static void umlDriverLock(struct uml_driver *driver)
{
116
    virMutexLock(&driver->lock);
117 118 119
}
static void umlDriverUnlock(struct uml_driver *driver)
{
120
    virMutexUnlock(&driver->lock);
121 122
}

123

124
static int umlOpenMonitor(struct uml_driver *driver,
125
                          virDomainObjPtr vm);
126
static int umlReadPidFile(struct uml_driver *driver,
127
                          virDomainObjPtr vm);
128 129
static void umlDomainEventQueue(struct uml_driver *driver,
                                virDomainEventPtr event);
130 131 132

static int umlStartVMDaemon(virConnectPtr conn,
                            struct uml_driver *driver,
133 134
                            virDomainObjPtr vm,
                            bool autoDestroy);
135

136
static void umlShutdownVMDaemon(struct uml_driver *driver,
J
Jiri Denemark 已提交
137 138
                                virDomainObjPtr vm,
                                virDomainShutoffReason reason);
139 140


141 142 143 144
static int umlMonitorCommand(const struct uml_driver *driver,
                             const virDomainObjPtr vm,
                             const char *cmd,
                             char **reply);
145 146 147

static struct uml_driver *uml_driver = NULL;

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
static int
umlVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
                   virHashIterator iter, void *data)
{
    virHashForEach(uml_driver->domains.objs, iter, data);

    return 0;
}

static void
umlVMDriverLock(void)
{
    umlDriverLock(uml_driver);
}

static void
umlVMDriverUnlock(void)
{
    umlDriverUnlock(uml_driver);
}

static virNWFilterCallbackDriver umlCallbackDriver = {
    .name = "UML",
    .vmFilterRebuild = umlVMFilterRebuild,
    .vmDriverLock = umlVMDriverLock,
    .vmDriverUnlock = umlVMDriverUnlock,
};

176 177 178 179 180 181
struct umlAutostartData {
    struct uml_driver *driver;
    virConnectPtr conn;
};

static void
182
umlAutostartDomain(void *payload, const void *name ATTRIBUTE_UNUSED, void *opaque)
183 184 185 186 187 188
{
    virDomainObjPtr vm = payload;
    const struct umlAutostartData *data = opaque;

    virDomainObjLock(vm);
    if (vm->autostart &&
D
Daniel P. Berrange 已提交
189
        !virDomainObjIsActive(vm)) {
190
        int ret;
191
        virResetLastError();
192
        ret = umlStartVMDaemon(data->conn, data->driver, vm, false);
193 194
        virDomainAuditStart(vm, "booted", ret >= 0);
        if (ret < 0) {
195 196
            virErrorPtr err = virGetLastError();
            VIR_ERROR(_("Failed to autostart VM '%s': %s"),
197
                      vm->def->name, err ? err->message : _("unknown error"));
198 199 200 201 202 203 204
        } else {
            virDomainEventPtr event =
                virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED);
            if (event)
                umlDomainEventQueue(data->driver, event);
205 206 207 208
        }
    }
    virDomainObjUnlock(vm);
}
209 210 211

static void
umlAutostartConfigs(struct uml_driver *driver) {
212 213 214 215 216
    /* XXX: Figure out a better way todo this. The domain
     * startup code needs a connection handle in order
     * to lookup the bridge associated with a virtual
     * network
     */
217 218 219
    virConnectPtr conn = virConnectOpen(driver->privileged ?
                                        "uml:///system" :
                                        "uml:///session");
220
    /* Ignoring NULL conn which is mostly harmless here */
221

222 223
    struct umlAutostartData data = { driver, conn };

224
    umlDriverLock(driver);
225
    virHashForEach(driver->domains.objs, umlAutostartDomain, &data);
226
    umlDriverUnlock(driver);
227

228 229
    if (conn)
        virConnectClose(conn);
230 231 232 233
}


static int
234
umlIdentifyOneChrPTY(struct uml_driver *driver,
235 236 237 238 239 240 241
                     virDomainObjPtr dom,
                     virDomainChrDefPtr def,
                     const char *dev)
{
    char *cmd;
    char *res = NULL;
    int retries = 0;
242
    if (virAsprintf(&cmd, "config %s%d", dev, def->target.port) < 0) {
243
        virReportOOMError();
244 245 246
        return -1;
    }
requery:
247
    if (umlMonitorCommand(driver, dom, cmd, &res) < 0)
248
        return -1;
249

250
    if (res && STRPREFIX(res, "pts:")) {
251 252
        VIR_FREE(def->source.data.file.path);
        if ((def->source.data.file.path = strdup(res + 4)) == NULL) {
253
            virReportOOMError();
254 255 256 257
            VIR_FREE(res);
            VIR_FREE(cmd);
            return -1;
        }
258
    } else if (!res || STRPREFIX(res, "pts")) {
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
        /* It can take a while to startup, so retry for
           upto 5 seconds */
        /* XXX should do this in a better non-blocking
           way somehow ...perhaps register a timer */
        if (retries++ < 50) {
            usleep(1000*10);
            goto requery;
        }
    }

    VIR_FREE(cmd);
    VIR_FREE(res);
    return 0;
}

static int
275
umlIdentifyChrPTY(struct uml_driver *driver,
276 277 278 279
                  virDomainObjPtr dom)
{
    int i;

280
    for (i = 0 ; i < dom->def->nconsoles; i++)
281
        if (dom->def->consoles[i]->source.type == VIR_DOMAIN_CHR_TYPE_PTY)
282
        if (umlIdentifyOneChrPTY(driver, dom,
283
                                 dom->def->consoles[i], "con") < 0)
284 285 286
            return -1;

    for (i = 0 ; i < dom->def->nserials; i++)
287
        if (dom->def->serials[i]->source.type == VIR_DOMAIN_CHR_TYPE_PTY &&
288
            umlIdentifyOneChrPTY(driver, dom,
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
                                 dom->def->serials[i], "ssl") < 0)
            return -1;

    return 0;
}

static void
umlInotifyEvent(int watch,
                int fd,
                int events ATTRIBUTE_UNUSED,
                void *data)
{
    char buf[1024];
    struct inotify_event *e;
    int got;
    char *tmp, *name;
    struct uml_driver *driver = data;
    virDomainObjPtr dom;
307
    virDomainEventPtr event = NULL;
308

309
    umlDriverLock(driver);
310
    if (watch != driver->inotifyWatch)
311
        goto cleanup;
312 313 314 315 316 317

reread:
    got = read(fd, buf, sizeof(buf));
    if (got == -1) {
        if (errno == EINTR)
            goto reread;
318
        goto cleanup;
319 320 321 322 323
    }

    tmp = buf;
    while (got) {
        if (got < sizeof(struct inotify_event))
324
            goto cleanup; /* bad */
325 326 327 328 329 330

        e = (struct inotify_event *)tmp;
        tmp += sizeof(struct inotify_event);
        got -= sizeof(struct inotify_event);

        if (got < e->len)
331
            goto cleanup;
332 333 334 335 336 337 338 339 340 341 342 343 344

        tmp += e->len;
        got -= e->len;

        name = (char *)&(e->name);

        dom = virDomainFindByName(&driver->domains, name);

        if (!dom) {
            continue;
        }

        if (e->mask & IN_DELETE) {
345
            VIR_DEBUG("Got inotify domain shutdown '%s'", name);
D
Daniel P. Berrange 已提交
346
            if (!virDomainObjIsActive(dom)) {
347
                virDomainObjUnlock(dom);
348 349 350
                continue;
            }

351
            umlShutdownVMDaemon(driver, dom, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
352
            virDomainAuditStop(dom, "shutdown");
353 354 355
            event = virDomainEventNewFromObj(dom,
                                             VIR_DOMAIN_EVENT_STOPPED,
                                             VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN);
356 357 358 359 360
            if (!dom->persistent) {
                virDomainRemoveInactive(&driver->domains,
                                        dom);
                dom = NULL;
            }
361
        } else if (e->mask & (IN_CREATE | IN_MODIFY)) {
362
            VIR_DEBUG("Got inotify domain startup '%s'", name);
D
Daniel P. Berrange 已提交
363
            if (virDomainObjIsActive(dom)) {
364
                virDomainObjUnlock(dom);
365 366 367
                continue;
            }

368
            if (umlReadPidFile(driver, dom) < 0) {
369
                virDomainObjUnlock(dom);
370 371 372 373
                continue;
            }

            dom->def->id = driver->nextvmid++;
J
Jiri Denemark 已提交
374 375
            virDomainObjSetState(dom, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_BOOTED);
376

377
            if (umlOpenMonitor(driver, dom) < 0) {
378
                VIR_WARN("Could not open monitor for new domain");
379
                umlShutdownVMDaemon(driver, dom,
J
Jiri Denemark 已提交
380
                                    VIR_DOMAIN_SHUTOFF_FAILED);
381
                virDomainAuditStop(dom, "failed");
382 383 384
                event = virDomainEventNewFromObj(dom,
                                                 VIR_DOMAIN_EVENT_STOPPED,
                                                 VIR_DOMAIN_EVENT_STOPPED_FAILED);
385 386 387 388 389
                if (!dom->persistent) {
                    virDomainRemoveInactive(&driver->domains,
                                            dom);
                    dom = NULL;
                }
390
            } else if (umlIdentifyChrPTY(driver, dom) < 0) {
391
                VIR_WARN("Could not identify character devices for new domain");
392
                umlShutdownVMDaemon(driver, dom,
J
Jiri Denemark 已提交
393
                                    VIR_DOMAIN_SHUTOFF_FAILED);
394
                virDomainAuditStop(dom, "failed");
395 396 397
                event = virDomainEventNewFromObj(dom,
                                                 VIR_DOMAIN_EVENT_STOPPED,
                                                 VIR_DOMAIN_EVENT_STOPPED_FAILED);
398 399 400 401 402
                if (!dom->persistent) {
                    virDomainRemoveInactive(&driver->domains,
                                            dom);
                    dom = NULL;
                }
403
            }
404
        }
405 406
        if (dom)
            virDomainObjUnlock(dom);
407
    }
408 409

cleanup:
410 411
    if (event)
        umlDomainEventQueue(driver, event);
412
    umlDriverUnlock(driver);
413 414 415 416 417 418 419 420
}

/**
 * umlStartup:
 *
 * Initialization function for the Uml daemon
 */
static int
421 422
umlStartup(int privileged)
{
423
    char *base = NULL;
424
    char *userdir = NULL;
425 426 427 428

    if (VIR_ALLOC(uml_driver) < 0)
        return -1;

429 430
    uml_driver->privileged = privileged;

431 432 433 434
    if (virMutexInit(&uml_driver->lock) < 0) {
        VIR_FREE(uml_driver);
        return -1;
    }
435 436
    umlDriverLock(uml_driver);

437 438
    /* Don't have a dom0 so start from 1 */
    uml_driver->nextvmid = 1;
439
    uml_driver->inotifyWatch = -1;
440

441 442 443
    if (virDomainObjListInit(&uml_driver->domains) < 0)
        goto error;

444
    uml_driver->domainEventState = virDomainEventStateNew();
445 446 447
    if (!uml_driver->domainEventState)
        goto error;

448
    userdir = virGetUserDirectory();
449
    if (!userdir)
450
        goto error;
451

452
    if (privileged) {
453
        if (virAsprintf(&uml_driver->logDir,
454
                        "%s/log/libvirt/uml", LOCALSTATEDIR) == -1)
455 456
            goto out_of_memory;

457
        if ((base = strdup (SYSCONFDIR "/libvirt")) == NULL)
458
            goto out_of_memory;
459 460

        if (virAsprintf(&uml_driver->monitorDir,
461
                        "%s/run/libvirt/uml-guest", LOCALSTATEDIR) == -1)
462
            goto out_of_memory;
463
    } else {
464
        base = virGetUserConfigDirectory();
465 466
        if (!base)
            goto error;
467

468
        if (virAsprintf(&uml_driver->logDir,
469
                        "%s/uml/log", base) == -1)
470 471
            goto out_of_memory;

472 473 474 475
        if (virAsprintf(&uml_driver->monitorDir,
                        "%s/.uml", userdir) == -1)
            goto out_of_memory;
    }
476

477
    /* Configuration paths are either $XDG_CONFIG_HOME/libvirt/uml/... (session) or
478 479
     * /etc/libvirt/uml/... (system).
     */
480
    if (virAsprintf(&uml_driver->configDir, "%s/uml", base) == -1)
481 482
        goto out_of_memory;

483
    if (virAsprintf(&uml_driver->autostartDir, "%s/uml/autostart", base) == -1)
484 485 486 487 488 489 490
        goto out_of_memory;

    VIR_FREE(base);

    if ((uml_driver->caps = umlCapsInit()) == NULL)
        goto out_of_memory;

491 492
    uml_driver->caps->privateDataAllocFunc = umlDomainObjPrivateAlloc;
    uml_driver->caps->privateDataFreeFunc = umlDomainObjPrivateFree;
493 494

    if ((uml_driver->inotifyFD = inotify_init()) < 0) {
495
        VIR_ERROR(_("cannot initialize inotify"));
496
        goto error;
497 498
    }

499
    if (virFileMakePath(uml_driver->monitorDir) < 0) {
500
        char ebuf[1024];
D
Daniel Veillard 已提交
501
        VIR_ERROR(_("Failed to create monitor directory %s: %s"),
502
                  uml_driver->monitorDir, virStrerror(errno, ebuf, sizeof(ebuf)));
503
        goto error;
504 505
    }

506
    VIR_INFO("Adding inotify watch on %s", uml_driver->monitorDir);
507 508 509
    if (inotify_add_watch(uml_driver->inotifyFD,
                          uml_driver->monitorDir,
                          IN_CREATE | IN_MODIFY | IN_DELETE) < 0) {
510
        goto error;
511 512
    }

513 514
    if ((uml_driver->inotifyWatch =
         virEventAddHandle(uml_driver->inotifyFD, POLLIN,
515 516
                           umlInotifyEvent, uml_driver, NULL)) < 0)
        goto error;
517

518 519 520
    if (umlProcessAutoDestroyInit(uml_driver) < 0)
        goto error;

521
    if (virDomainLoadAllConfigs(uml_driver->caps,
522 523 524
                                &uml_driver->domains,
                                uml_driver->configDir,
                                uml_driver->autostartDir,
M
Matthias Bolte 已提交
525 526
                                0, 1 << VIR_DOMAIN_VIRT_UML,
                                NULL, NULL) < 0)
527 528
        goto error;

529 530
    umlDriverUnlock(uml_driver);

531 532
    umlAutostartConfigs(uml_driver);

533 534
    VIR_FREE(userdir);

535
    virNWFilterRegisterCallbackDriver(&umlCallbackDriver);
536 537
    return 0;

538
out_of_memory:
539
    VIR_ERROR(_("umlStartup: out of memory"));
540 541

error:
542
    VIR_FREE(userdir);
543
    VIR_FREE(base);
544 545
    umlDriverUnlock(uml_driver);
    umlShutdown();
546 547 548
    return -1;
}

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
static void umlNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
{
    struct uml_driver *driver = opaque;

    if (newVM) {
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED);
        if (event)
            umlDomainEventQueue(driver, event);
    }
}


564 565 566 567 568 569 570 571 572 573 574
/**
 * umlReload:
 *
 * Function to restart the Uml daemon, it will recheck the configuration
 * files and update its state and the networking
 */
static int
umlReload(void) {
    if (!uml_driver)
        return 0;

575
    umlDriverLock(uml_driver);
576
    virDomainLoadAllConfigs(uml_driver->caps,
577 578 579
                            &uml_driver->domains,
                            uml_driver->configDir,
                            uml_driver->autostartDir,
M
Matthias Bolte 已提交
580
                            0, 1 << VIR_DOMAIN_VIRT_UML,
581 582
                            umlNotifyLoadDomain, uml_driver);
    umlDriverUnlock(uml_driver);
583 584 585 586 587 588 589 590 591 592 593 594 595 596

    return 0;
}

/**
 * umlActive:
 *
 * Checks if the Uml daemon is active, i.e. has an active domain or
 * an active network
 *
 * Returns 1 if active, 0 otherwise
 */
static int
umlActive(void) {
597
    int active = 0;
598 599 600 601

    if (!uml_driver)
        return 0;

602
    umlDriverLock(uml_driver);
603
    active = virDomainObjListNumOfDomains(&uml_driver->domains, 1);
604
    umlDriverUnlock(uml_driver);
605

606
    return active;
607 608
}

609
static void
610
umlShutdownOneVM(void *payload, const void *name ATTRIBUTE_UNUSED, void *opaque)
611 612 613 614 615
{
    virDomainObjPtr dom = payload;
    struct uml_driver *driver = opaque;

    virDomainObjLock(dom);
616
    if (virDomainObjIsActive(dom)) {
617
        umlShutdownVMDaemon(driver, dom, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
618 619
        virDomainAuditStop(dom, "shutdown");
    }
620 621 622
    virDomainObjUnlock(dom);
}

623 624 625 626 627 628 629 630 631 632
/**
 * umlShutdown:
 *
 * Shutdown the Uml daemon, it will stop all active domains and networks
 */
static int
umlShutdown(void) {
    if (!uml_driver)
        return -1;

633
    umlDriverLock(uml_driver);
634
    virNWFilterRegisterCallbackDriver(&umlCallbackDriver);
635 636
    if (uml_driver->inotifyWatch != -1)
        virEventRemoveHandle(uml_driver->inotifyWatch);
637
    VIR_FORCE_CLOSE(uml_driver->inotifyFD);
638 639
    virCapabilitiesFree(uml_driver->caps);

640 641 642
    /* shutdown active VMs
     * XXX allow them to stay around & reconnect */
    virHashForEach(uml_driver->domains.objs, umlShutdownOneVM, uml_driver);
643

644
    virDomainObjListDeinit(&uml_driver->domains);
645

646 647
    virDomainEventStateFree(uml_driver->domainEventState);

648 649 650 651 652
    VIR_FREE(uml_driver->logDir);
    VIR_FREE(uml_driver->configDir);
    VIR_FREE(uml_driver->autostartDir);
    VIR_FREE(uml_driver->monitorDir);

653 654
    umlProcessAutoDestroyShutdown(uml_driver);

655
    umlDriverUnlock(uml_driver);
656
    virMutexDestroy(&uml_driver->lock);
657 658 659 660 661 662
    VIR_FREE(uml_driver);

    return 0;
}


663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
static int umlProcessAutoDestroyInit(struct uml_driver *driver)
{
    if (!(driver->autodestroy = virHashCreate(5, NULL)))
        return -1;

    return 0;
}

struct umlProcessAutoDestroyData {
    struct uml_driver *driver;
    virConnectPtr conn;
};

static void umlProcessAutoDestroyDom(void *payload,
                                     const void *name,
                                     void *opaque)
{
    struct umlProcessAutoDestroyData *data = opaque;
    virConnectPtr conn = payload;
    const char *uuidstr = name;
    unsigned char uuid[VIR_UUID_BUFLEN];
    virDomainObjPtr dom;
    virDomainEventPtr event = NULL;

    VIR_DEBUG("conn=%p uuidstr=%s thisconn=%p", conn, uuidstr, data->conn);

    if (data->conn != conn)
        return;

    if (virUUIDParse(uuidstr, uuid) < 0) {
        VIR_WARN("Failed to parse %s", uuidstr);
        return;
    }

    if (!(dom = virDomainFindByUUID(&data->driver->domains,
                                    uuid))) {
        VIR_DEBUG("No domain object to kill");
        return;
    }

    VIR_DEBUG("Killing domain");
    umlShutdownVMDaemon(data->driver, dom, VIR_DOMAIN_SHUTOFF_DESTROYED);
    virDomainAuditStop(dom, "destroyed");
    event = virDomainEventNewFromObj(dom,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);

    if (dom && !dom->persistent)
        virDomainRemoveInactive(&data->driver->domains, dom);

    if (dom)
        virDomainObjUnlock(dom);
    if (event)
        umlDomainEventQueue(data->driver, event);
    virHashRemoveEntry(data->driver->autodestroy, uuidstr);
}

/*
 * Precondition: driver is locked
 */
static void umlProcessAutoDestroyRun(struct uml_driver *driver, virConnectPtr conn)
{
    struct umlProcessAutoDestroyData data = {
        driver, conn
    };
    VIR_DEBUG("conn=%p", conn);
    virHashForEach(driver->autodestroy, umlProcessAutoDestroyDom, &data);
}

static void umlProcessAutoDestroyShutdown(struct uml_driver *driver)
{
    virHashFree(driver->autodestroy);
}

static int umlProcessAutoDestroyAdd(struct uml_driver *driver,
                                    virDomainObjPtr vm,
                                    virConnectPtr conn)
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virUUIDFormat(vm->def->uuid, uuidstr);
    VIR_DEBUG("vm=%s uuid=%s conn=%p", vm->def->name, uuidstr, conn);
    if (virHashAddEntry(driver->autodestroy, uuidstr, conn) < 0)
        return -1;
    return 0;
}

static int umlProcessAutoDestroyRemove(struct uml_driver *driver,
                                       virDomainObjPtr vm)
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virUUIDFormat(vm->def->uuid, uuidstr);
    VIR_DEBUG("vm=%s uuid=%s", vm->def->name, uuidstr);
    if (virHashRemoveEntry(driver->autodestroy, uuidstr) < 0)
        return -1;
    return 0;
}


761
static int umlReadPidFile(struct uml_driver *driver,
762 763 764 765 766 767 768 769
                          virDomainObjPtr vm)
{
    int rc = -1;
    FILE *file;
    char *pidfile = NULL;
    int retries = 0;

    vm->pid = -1;
770 771
    if (virAsprintf(&pidfile, "%s/%s/pid",
                    driver->monitorDir, vm->def->name) < 0) {
772
        virReportOOMError();
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
        return -1;
    }

reopen:
    if (!(file = fopen(pidfile, "r"))) {
        if (errno == ENOENT &&
            retries++ < 50) {
            usleep(1000 * 100);
            goto reopen;
        }
        goto cleanup;
    }

    if (fscanf(file, "%d", &vm->pid) != 1) {
        errno = EINVAL;
788
        VIR_FORCE_FCLOSE(file);
789 790 791
        goto cleanup;
    }

792
    if (VIR_FCLOSE(file) < 0)
793 794 795 796 797 798
        goto cleanup;

    rc = 0;

 cleanup:
    if (rc != 0)
799
        virReportSystemError(errno,
800 801
                             _("failed to read pid: %s"),
                             pidfile);
802 803 804 805
    VIR_FREE(pidfile);
    return rc;
}

806
static int umlMonitorAddress(const struct uml_driver *driver,
807 808 809
                             virDomainObjPtr vm,
                             struct sockaddr_un *addr) {
    char *sockname;
C
Chris Lalancette 已提交
810
    int retval = 0;
811

812 813
    if (virAsprintf(&sockname, "%s/%s/mconsole",
                    driver->monitorDir, vm->def->name) < 0) {
814
        virReportOOMError();
815 816 817
        return -1;
    }

818
    memset(addr, 0, sizeof(*addr));
819
    addr->sun_family = AF_UNIX;
C
Chris Lalancette 已提交
820
    if (virStrcpyStatic(addr->sun_path, sockname) == NULL) {
821
        virReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
822 823 824
                       _("Unix path %s too long for destination"), sockname);
        retval = -1;
    }
825
    VIR_FREE(sockname);
C
Chris Lalancette 已提交
826
    return retval;
827 828
}

829
static int umlOpenMonitor(struct uml_driver *driver,
830 831 832 833
                          virDomainObjPtr vm) {
    struct sockaddr_un addr;
    struct stat sb;
    int retries = 0;
834
    umlDomainObjPrivatePtr priv = vm->privateData;
835

836
    if (umlMonitorAddress(driver, vm, &addr) < 0)
837 838
        return -1;

839
    VIR_DEBUG("Dest address for monitor is '%s'", addr.sun_path);
840 841 842
restat:
    if (stat(addr.sun_path, &sb) < 0) {
        if (errno == ENOENT &&
843
            retries++ < 50) {
844 845 846 847 848 849
            usleep(1000 * 100);
            goto restat;
        }
        return -1;
    }

850
    if ((priv->monitor = socket(PF_UNIX, SOCK_DGRAM, 0)) < 0) {
851
        virReportSystemError(errno,
852
                             "%s", _("cannot open socket"));
853 854 855
        return -1;
    }

856
    memset(addr.sun_path, 0, sizeof(addr.sun_path));
E
Eric Blake 已提交
857 858
    snprintf(addr.sun_path + 1, sizeof(addr.sun_path) - 1,
             "libvirt-uml-%u", vm->pid);
859
    VIR_DEBUG("Reply address for monitor is '%s'", addr.sun_path+1);
860
    if (bind(priv->monitor, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
861
        virReportSystemError(errno,
862
                             "%s", _("cannot bind socket"));
863
        VIR_FORCE_CLOSE(priv->monitor);
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
        return -1;
    }

    return 0;
}


#define MONITOR_MAGIC 0xcafebabe
#define MONITOR_BUFLEN 512
#define MONITOR_VERSION 2

struct monitor_request {
    uint32_t magic;
    uint32_t version;
    uint32_t length;
    char data[MONITOR_BUFLEN];
};

struct monitor_response {
    uint32_t error;
    uint32_t extra;
    uint32_t length;
    char data[MONITOR_BUFLEN];
};


890
static int umlMonitorCommand(const struct uml_driver *driver,
891 892 893 894 895 896 897 898 899 900
                             const virDomainObjPtr vm,
                             const char *cmd,
                             char **reply)
{
    struct monitor_request req;
    struct monitor_response res;
    char *retdata = NULL;
    int retlen = 0, ret = 0;
    struct sockaddr_un addr;
    unsigned int addrlen;
901
    umlDomainObjPrivatePtr priv = vm->privateData;
902

903 904
    VIR_DEBUG("Run command '%s'", cmd);

905 906
    *reply = NULL;

907
    if (umlMonitorAddress(driver, vm, &addr) < 0)
908 909 910 911 912 913 914
        return -1;

    memset(&req, 0, sizeof(req));
    req.magic = MONITOR_MAGIC;
    req.version = MONITOR_VERSION;
    req.length = strlen(cmd);
    if (req.length > (MONITOR_BUFLEN-1)) {
915
        virReportSystemError(EINVAL,
916 917
                             _("cannot send too long command %s (%d bytes)"),
                             cmd, req.length);
918 919
        return -1;
    }
C
Chris Lalancette 已提交
920
    if (virStrcpyStatic(req.data, cmd) == NULL) {
921
        virReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
922 923 924
                       _("Command %s too long for destination"), cmd);
        return -1;
    }
925

926 927
    if (sendto(priv->monitor, &req, sizeof(req), 0,
               (struct sockaddr *)&addr, sizeof(addr)) != sizeof(req)) {
928
        virReportSystemError(errno,
929 930
                             _("cannot send command %s"),
                             cmd);
931 932 933 934
        return -1;
    }

    do {
E
Eric Blake 已提交
935
        ssize_t nbytes;
936
        addrlen = sizeof(addr);
937
        nbytes = recvfrom(priv->monitor, &res, sizeof(res), 0,
938
                          (struct sockaddr *)&addr, &addrlen);
E
Eric Blake 已提交
939 940 941
        if (nbytes < 0) {
            if (errno == EAGAIN || errno == EINTR)
                continue;
942
            virReportSystemError(errno, _("cannot read reply %s"), cmd);
943 944
            goto error;
        }
945 946 947
        /* Ensure res.length is safe to read before validating its value.  */
        if (nbytes < offsetof(struct monitor_request, data) ||
            nbytes < offsetof(struct monitor_request, data) + res.length) {
948 949 950
            virReportSystemError(0, _("incomplete reply %s"), cmd);
            goto error;
        }
951 952

        if (VIR_REALLOC_N(retdata, retlen + res.length) < 0) {
953
            virReportOOMError();
954 955 956 957 958 959 960 961 962 963 964
            goto error;
        }
        memcpy(retdata + retlen, res.data, res.length);
        retlen += res.length - 1;
        retdata[retlen] = '\0';

        if (res.error)
            ret = -1;

    } while (res.extra);

965 966
    VIR_DEBUG("Command reply is '%s'", NULLSTR(retdata));

967 968 969 970
    if (ret < 0)
        VIR_FREE(retdata);
    else
        *reply = retdata;
971 972 973 974 975 976 977 978 979

    return ret;

error:
    VIR_FREE(retdata);
    return -1;
}


980
static void umlCleanupTapDevices(virDomainObjPtr vm) {
981 982 983 984 985 986 987 988 989
    int i;

    for (i = 0 ; i < vm->def->nnets ; i++) {
        virDomainNetDefPtr def = vm->def->nets[i];

        if (def->type != VIR_DOMAIN_NET_TYPE_BRIDGE &&
            def->type != VIR_DOMAIN_NET_TYPE_NETWORK)
            continue;

990
        ignore_value(virNetDevTapDelete(def->ifname));
991 992 993
    }
}

994 995
static int umlStartVMDaemon(virConnectPtr conn,
                            struct uml_driver *driver,
996 997
                            virDomainObjPtr vm,
                            bool autoDestroy) {
998
    int ret = -1;
999 1000
    char *logfile;
    int logfd = -1;
1001
    umlDomainObjPrivatePtr priv = vm->privateData;
D
Daniel P. Berrange 已提交
1002
    virCommandPtr cmd = NULL;
1003
    size_t i;
1004

D
Daniel P. Berrange 已提交
1005
    if (virDomainObjIsActive(vm)) {
1006
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
1007
                       _("VM is already active"));
1008 1009 1010 1011
        return -1;
    }

    if (!vm->def->os.kernel) {
1012
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1013
                       _("no kernel specified"));
1014 1015 1016 1017 1018 1019
        return -1;
    }
    /* Make sure the binary we are about to try exec'ing exists.
     * Technically we could catch the exec() failure, but that's
     * in a sub-process so its hard to feed back a useful error
     */
E
Eric Blake 已提交
1020
    if (!virFileIsExecutable(vm->def->os.kernel)) {
1021
        virReportSystemError(errno,
1022 1023
                             _("Cannot find UML kernel %s"),
                             vm->def->os.kernel);
1024 1025 1026
        return -1;
    }

1027
    if (virFileMakePath(driver->logDir) < 0) {
1028
        virReportSystemError(errno,
1029 1030
                             _("cannot create log directory %s"),
                             driver->logDir);
1031 1032 1033
        return -1;
    }

1034 1035
    if (virAsprintf(&logfile, "%s/%s.log",
                    driver->logDir, vm->def->name) < 0) {
1036
        virReportOOMError();
1037 1038 1039 1040 1041
        return -1;
    }

    if ((logfd = open(logfile, O_CREAT | O_TRUNC | O_WRONLY,
                      S_IRUSR | S_IWUSR)) < 0) {
1042
        virReportSystemError(errno,
1043 1044
                             _("failed to create logfile %s"),
                             logfile);
1045 1046 1047 1048 1049
        VIR_FREE(logfile);
        return -1;
    }
    VIR_FREE(logfile);

E
Eric Blake 已提交
1050 1051 1052
    if (virSetCloseExec(logfd) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to set VM logfile close-on-exec flag"));
1053
        VIR_FORCE_CLOSE(logfd);
1054 1055 1056
        return -1;
    }

1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
    /* Do this upfront, so any part of the startup process can add
     * runtime state to vm->def that won't be persisted. This let's us
     * report implicit runtime defaults in the XML, like vnc listen/socket
     */
    VIR_DEBUG("Setting current domain def as transient");
    if (virDomainObjSetDefTransient(driver->caps, vm, true) < 0) {
        VIR_FORCE_CLOSE(logfd);
        return -1;
    }

1067 1068
    if (!(cmd = umlBuildCommandLine(conn, driver, vm)))
        goto cleanup;
1069

1070 1071 1072 1073 1074 1075 1076 1077
    for (i = 0 ; i < vm->def->nconsoles ; i++) {
        VIR_FREE(vm->def->consoles[i]->info.alias);
        if (virAsprintf(&vm->def->consoles[i]->info.alias, "console%zu", i) < 0) {
            virReportOOMError();
            goto cleanup;
        }
    }

D
Daniel P. Berrange 已提交
1078
    virCommandWriteArgLog(cmd, logfd);
1079

1080
    priv->monitor = -1;
1081

D
Daniel P. Berrange 已提交
1082 1083 1084 1085 1086 1087
    virCommandClearCaps(cmd);
    virCommandSetOutputFD(cmd, &logfd);
    virCommandSetErrorFD(cmd, &logfd);
    virCommandDaemonize(cmd);

    ret = virCommandRun(cmd, NULL);
1088 1089
    if (ret < 0)
        goto cleanup;
1090

1091
    if (autoDestroy &&
1092
        (ret = umlProcessAutoDestroyAdd(driver, vm, conn)) < 0)
1093 1094
        goto cleanup;

1095
    ret = virDomainObjSetDefTransient(driver->caps, vm, false);
1096
cleanup:
1097
    VIR_FORCE_CLOSE(logfd);
D
Daniel P. Berrange 已提交
1098
    virCommandFree(cmd);
1099

1100 1101
    if (ret < 0) {
        virDomainConfVMNWFilterTeardown(vm);
1102
        umlCleanupTapDevices(vm);
1103 1104 1105 1106 1107 1108
        if (vm->newDef) {
            virDomainDefFree(vm->def);
            vm->def = vm->newDef;
            vm->def->id = -1;
            vm->newDef = NULL;
        }
1109 1110
    }

1111 1112
    /* NB we don't mark it running here - we do that async
       with inotify */
1113 1114 1115
    /* XXX what if someone else tries to start it again
       before we get the inotification ? Sounds like
       trouble.... */
1116
    /* XXX this is bad for events too. must fix this better */
1117 1118 1119 1120

    return ret;
}

1121
static void umlShutdownVMDaemon(struct uml_driver *driver,
J
Jiri Denemark 已提交
1122 1123
                                virDomainObjPtr vm,
                                virDomainShutoffReason reason)
1124 1125
{
    int ret;
1126 1127
    umlDomainObjPrivatePtr priv = vm->privateData;

D
Daniel P. Berrange 已提交
1128
    if (!virDomainObjIsActive(vm))
1129 1130
        return;

1131
    virKillProcess(vm->pid, SIGTERM);
1132

1133
    VIR_FORCE_CLOSE(priv->monitor);
1134 1135

    if ((ret = waitpid(vm->pid, NULL, 0)) != vm->pid) {
1136
        VIR_WARN("Got unexpected pid %d != %d",
1137 1138 1139 1140 1141
               ret, vm->pid);
    }

    vm->pid = -1;
    vm->def->id = -1;
J
Jiri Denemark 已提交
1142
    virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF, reason);
1143

1144
    virDomainConfVMNWFilterTeardown(vm);
1145 1146 1147 1148
    umlCleanupTapDevices(vm);

    /* Stop autodestroy in case guest is restarted */
    umlProcessAutoDestroyRemove(driver, vm);
1149

1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
    if (vm->newDef) {
        virDomainDefFree(vm->def);
        vm->def = vm->newDef;
        vm->def->id = -1;
        vm->newDef = NULL;
    }
}


static virDrvOpenStatus umlOpen(virConnectPtr conn,
                                virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
1161 1162 1163 1164
                                unsigned int flags)
{
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

1165 1166 1167
    if (conn->uri == NULL) {
        if (uml_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;
1168

1169 1170 1171
        if (!(conn->uri = virURIParse(uml_driver->privileged ?
                                      "uml:///system" :
                                      "uml:///session")))
1172 1173 1174 1175 1176 1177 1178 1179 1180
            return VIR_DRV_OPEN_ERROR;
    } else {
        if (conn->uri->scheme == NULL ||
            STRNEQ (conn->uri->scheme, "uml"))
            return VIR_DRV_OPEN_DECLINED;

        /* Allow remote driver to deal with URIs with hostname server */
        if (conn->uri->server != NULL)
            return VIR_DRV_OPEN_DECLINED;
1181 1182


1183
        /* Check path and tell them correct path if they made a mistake */
1184
        if (uml_driver->privileged) {
1185
            if (STRNEQ (conn->uri->path, "/system") &&
1186
                STRNEQ (conn->uri->path, "/session")) {
1187
                virReportError(VIR_ERR_INTERNAL_ERROR,
1188 1189 1190 1191 1192 1193
                               _("unexpected UML URI path '%s', try uml:///system"),
                               conn->uri->path);
                return VIR_DRV_OPEN_ERROR;
            }
        } else {
            if (STRNEQ (conn->uri->path, "/session")) {
1194
                virReportError(VIR_ERR_INTERNAL_ERROR,
1195 1196 1197 1198
                               _("unexpected UML URI path '%s', try uml:///session"),
                               conn->uri->path);
                return VIR_DRV_OPEN_ERROR;
            }
1199
        }
1200 1201 1202

        /* URI was good, but driver isn't active */
        if (uml_driver == NULL) {
1203
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1204
                           _("uml state driver is not active"));
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
            return VIR_DRV_OPEN_ERROR;
        }
    }

    conn->privateData = uml_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

static int umlClose(virConnectPtr conn) {
1215 1216 1217
    struct uml_driver *driver = conn->privateData;

    umlDriverLock(driver);
1218
    umlProcessAutoDestroyRun(driver, conn);
1219
    umlDriverUnlock(driver);
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230

    conn->privateData = NULL;

    return 0;
}

static const char *umlGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
    return "UML";
}


1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
static int umlIsSecure(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    /* Trivially secure, since always inside the daemon */
    return 1;
}


static int umlIsEncrypted(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    /* Not encrypted, but remote driver takes care of that */
    return 0;
}


1245 1246 1247 1248 1249 1250
static int umlIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    return 1;
}


1251 1252 1253 1254
static char *umlGetCapabilities(virConnectPtr conn) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
    char *xml;

1255
    umlDriverLock(driver);
1256
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1257
        virReportOOMError();
1258
    umlDriverUnlock(driver);
1259 1260 1261 1262 1263 1264

    return xml;
}



1265
static int umlGetProcessInfo(unsigned long long *cpuTime, pid_t pid)
1266 1267
{
    char *proc;
1268 1269 1270
    FILE *pidinfo;
    unsigned long long usertime, systime;

1271
    if (virAsprintf(&proc, "/proc/%lld/stat", (long long) pid) < 0) {
1272 1273 1274 1275 1276 1277
        return -1;
    }

    if (!(pidinfo = fopen(proc, "r"))) {
        /* VM probably shut down, so fake 0 */
        *cpuTime = 0;
1278
        VIR_FREE(proc);
1279 1280 1281
        return 0;
    }

1282 1283
    VIR_FREE(proc);

1284 1285
    if (fscanf(pidinfo, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %llu %llu", &usertime, &systime) != 2) {
        umlDebug("not enough arg");
1286
        VIR_FORCE_FCLOSE(pidinfo);
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
        return -1;
    }

    /* We got jiffies
     * We want nanoseconds
     * _SC_CLK_TCK is jiffies per second
     * So calulate thus....
     */
    *cpuTime = 1000ull * 1000ull * 1000ull * (usertime + systime) / (unsigned long long)sysconf(_SC_CLK_TCK);

    umlDebug("Got %llu %llu %llu", usertime, systime, *cpuTime);

1299
    VIR_FORCE_FCLOSE(pidinfo);
1300 1301 1302 1303 1304 1305 1306 1307

    return 0;
}


static virDomainPtr umlDomainLookupByID(virConnectPtr conn,
                                          int id) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1308 1309
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1310

1311
    umlDriverLock(driver);
1312
    vm = virDomainFindByID(&driver->domains, id);
1313 1314
    umlDriverUnlock(driver);

1315
    if (!vm) {
1316
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
1317
        goto cleanup;
1318 1319 1320 1321
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1322 1323

cleanup:
1324 1325
    if (vm)
        virDomainObjUnlock(vm);
1326 1327
    return dom;
}
1328

1329 1330 1331
static virDomainPtr umlDomainLookupByUUID(virConnectPtr conn,
                                            const unsigned char *uuid) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1332 1333
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1334

1335
    umlDriverLock(driver);
1336
    vm = virDomainFindByUUID(&driver->domains, uuid);
1337 1338
    umlDriverUnlock(driver);

1339
    if (!vm) {
1340
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
1341
        goto cleanup;
1342 1343 1344 1345
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1346 1347

cleanup:
1348 1349
    if (vm)
        virDomainObjUnlock(vm);
1350 1351
    return dom;
}
1352

1353 1354 1355
static virDomainPtr umlDomainLookupByName(virConnectPtr conn,
                                            const char *name) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1356 1357
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1358

1359
    umlDriverLock(driver);
1360
    vm = virDomainFindByName(&driver->domains, name);
1361 1362
    umlDriverUnlock(driver);

1363
    if (!vm) {
1364
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
1365
        goto cleanup;
1366 1367 1368 1369
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1370 1371

cleanup:
1372 1373
    if (vm)
        virDomainObjUnlock(vm);
1374 1375 1376
    return dom;
}

1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387

static int umlDomainIsActive(virDomainPtr dom)
{
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr obj;
    int ret = -1;

    umlDriverLock(driver);
    obj = virDomainFindByUUID(&driver->domains, dom->uuid);
    umlDriverUnlock(driver);
    if (!obj) {
1388
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
        goto cleanup;
    }
    ret = virDomainObjIsActive(obj);

cleanup:
    if (obj)
        virDomainObjUnlock(obj);
    return ret;
}


static int umlDomainIsPersistent(virDomainPtr dom)
{
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr obj;
    int ret = -1;

    umlDriverLock(driver);
    obj = virDomainFindByUUID(&driver->domains, dom->uuid);
    umlDriverUnlock(driver);
    if (!obj) {
1410
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
        goto cleanup;
    }
    ret = obj->persistent;

cleanup:
    if (obj)
        virDomainObjUnlock(obj);
    return ret;
}

1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
static int umlDomainIsUpdated(virDomainPtr dom)
{
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr obj;
    int ret = -1;

    umlDriverLock(driver);
    obj = virDomainFindByUUID(&driver->domains, dom->uuid);
    umlDriverUnlock(driver);
    if (!obj) {
1431
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
1432 1433 1434 1435 1436 1437 1438 1439 1440
        goto cleanup;
    }
    ret = obj->updated;

cleanup:
    if (obj)
        virDomainObjUnlock(obj);
    return ret;
}
1441

1442
static int umlGetVersion(virConnectPtr conn, unsigned long *version) {
1443
    struct uml_driver *driver = conn->privateData;
1444
    struct utsname ut;
1445
    int ret = -1;
1446

1447
    umlDriverLock(driver);
1448 1449 1450 1451

    if (driver->umlVersion == 0) {
        uname(&ut);

1452
        if (virParseVersionString(ut.release, &driver->umlVersion, true) < 0) {
1453
            virReportError(VIR_ERR_INTERNAL_ERROR,
1454 1455 1456
                           _("cannot parse version %s"), ut.release);
            goto cleanup;
        }
1457 1458
    }

1459 1460 1461 1462 1463 1464
    *version = driver->umlVersion;
    ret = 0;

cleanup:
    umlDriverUnlock(driver);
    return ret;
1465 1466 1467
}

static int umlListDomains(virConnectPtr conn, int *ids, int nids) {
1468
    struct uml_driver *driver = conn->privateData;
1469
    int n;
1470

1471
    umlDriverLock(driver);
1472
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
1473
    umlDriverUnlock(driver);
1474

1475
    return n;
1476 1477
}
static int umlNumDomains(virConnectPtr conn) {
1478
    struct uml_driver *driver = conn->privateData;
1479
    int n;
1480

1481
    umlDriverLock(driver);
1482
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
1483
    umlDriverUnlock(driver);
1484 1485 1486 1487

    return n;
}
static virDomainPtr umlDomainCreate(virConnectPtr conn, const char *xml,
1488
                                      unsigned int flags) {
1489
    struct uml_driver *driver = conn->privateData;
1490
    virDomainDefPtr def;
1491
    virDomainObjPtr vm = NULL;
1492
    virDomainPtr dom = NULL;
1493
    virDomainEventPtr event = NULL;
1494

1495
    virCheckFlags(VIR_DOMAIN_START_AUTODESTROY, NULL);
1496

1497
    umlDriverLock(driver);
1498
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
1499
                                        1 << VIR_DOMAIN_VIRT_UML,
1500
                                        VIR_DOMAIN_XML_INACTIVE)))
1501
        goto cleanup;
1502

1503
    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
1504
        goto cleanup;
1505

1506
    if (!(vm = virDomainAssignDef(driver->caps,
1507
                                  &driver->domains,
1508
                                  def, false)))
1509 1510
        goto cleanup;
    def = NULL;
1511

1512 1513
    if (umlStartVMDaemon(conn, driver, vm,
                         (flags & VIR_DOMAIN_START_AUTODESTROY)) < 0) {
1514
        virDomainAuditStart(vm, "booted", false);
1515 1516
        virDomainRemoveInactive(&driver->domains,
                                vm);
1517 1518
        vm = NULL;
        goto cleanup;
1519
    }
1520
    virDomainAuditStart(vm, "booted", true);
1521 1522 1523
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
1524 1525 1526

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1527 1528 1529

cleanup:
    virDomainDefFree(def);
1530 1531
    if (vm)
        virDomainObjUnlock(vm);
1532 1533
    if (event)
        umlDomainEventQueue(driver, event);
1534
    umlDriverUnlock(driver);
1535 1536 1537 1538
    return dom;
}


1539 1540
static int umlDomainShutdownFlags(virDomainPtr dom,
                                  unsigned int flags) {
1541 1542
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1543
    char *info = NULL;
1544
    int ret = -1;
1545

1546 1547
    virCheckFlags(0, -1);

1548
    umlDriverLock(driver);
1549
    vm = virDomainFindByID(&driver->domains, dom->id);
1550
    umlDriverUnlock(driver);
1551
    if (!vm) {
1552
        virReportError(VIR_ERR_NO_DOMAIN,
1553
                       _("no domain with matching id %d"), dom->id);
1554
        goto cleanup;
1555 1556 1557 1558
    }

#if 0
    if (umlMonitorCommand(driver, vm, "system_powerdown", &info) < 0) {
1559
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
1560
                       _("shutdown operation failed"));
1561
        goto cleanup;
1562
    }
1563
    ret = 0;
1564 1565
#endif

1566 1567
cleanup:
    VIR_FREE(info);
1568 1569
    if (vm)
        virDomainObjUnlock(vm);
1570
    return ret;
1571 1572
}

1573 1574 1575 1576 1577
static int
umlDomainShutdown(virDomainPtr dom)
{
    return umlDomainShutdownFlags(dom, 0);
}
1578

1579 1580 1581 1582
static int
umlDomainDestroyFlags(virDomainPtr dom,
                      unsigned int flags)
{
1583 1584
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1585
    virDomainEventPtr event = NULL;
1586
    int ret = -1;
1587

1588 1589
    virCheckFlags(0, -1);

1590
    umlDriverLock(driver);
1591
    vm = virDomainFindByID(&driver->domains, dom->id);
1592
    if (!vm) {
1593
        virReportError(VIR_ERR_NO_DOMAIN,
1594
                       _("no domain with matching id %d"), dom->id);
1595
        goto cleanup;
1596 1597
    }

1598
    umlShutdownVMDaemon(driver, vm, VIR_DOMAIN_SHUTOFF_DESTROYED);
1599
    virDomainAuditStop(vm, "destroyed");
1600 1601 1602
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
1603
    if (!vm->persistent) {
1604 1605
        virDomainRemoveInactive(&driver->domains,
                                vm);
1606 1607 1608
        vm = NULL;
    }
    ret = 0;
1609

1610
cleanup:
1611 1612
    if (vm)
        virDomainObjUnlock(vm);
1613 1614
    if (event)
        umlDomainEventQueue(driver, event);
1615
    umlDriverUnlock(driver);
1616
    return ret;
1617 1618 1619
}


1620 1621 1622 1623 1624 1625
static int umlDomainDestroy(virDomainPtr dom)
{
    return umlDomainDestroyFlags(dom, 0);
}


1626
static char *umlDomainGetOSType(virDomainPtr dom) {
1627 1628 1629
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1630

1631
    umlDriverLock(driver);
1632
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1633
    umlDriverUnlock(driver);
1634
    if (!vm) {
1635
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
1636
                       _("no domain with matching uuid"));
1637
        goto cleanup;
1638 1639
    }

1640
    if (!(type = strdup(vm->def->os.type)))
1641
        virReportOOMError();
1642 1643

cleanup:
1644 1645
    if (vm)
        virDomainObjUnlock(vm);
1646 1647 1648 1649
    return type;
}

/* Returns max memory in kb, 0 if error */
1650 1651 1652
static unsigned long long
umlDomainGetMaxMemory(virDomainPtr dom)
{
1653 1654
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1655
    unsigned long long ret = 0;
1656

1657
    umlDriverLock(driver);
1658
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1659 1660
    umlDriverUnlock(driver);

1661 1662 1663 1664
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1665
        virReportError(VIR_ERR_NO_DOMAIN,
1666 1667
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
1668
    }
1669
    ret = vm->def->mem.max_balloon;
1670

1671
cleanup:
1672 1673
    if (vm)
        virDomainObjUnlock(vm);
1674
    return ret;
1675 1676 1677
}

static int umlDomainSetMaxMemory(virDomainPtr dom, unsigned long newmax) {
1678 1679 1680
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1681

1682
    umlDriverLock(driver);
1683
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1684 1685
    umlDriverUnlock(driver);

1686 1687 1688 1689
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1690
        virReportError(VIR_ERR_NO_DOMAIN,
1691
                       _("no domain with matching uuid '%s'"), uuidstr);
1692
        goto cleanup;
1693 1694
    }

1695
    if (newmax < vm->def->mem.cur_balloon) {
1696
        virReportError(VIR_ERR_INVALID_ARG, "%s",
1697
                       _("cannot set max memory lower than current memory"));
1698
        goto cleanup;
1699 1700
    }

1701
    vm->def->mem.max_balloon = newmax;
1702 1703 1704
    ret = 0;

cleanup:
1705 1706
    if (vm)
        virDomainObjUnlock(vm);
1707
    return ret;
1708 1709 1710
}

static int umlDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
1711 1712 1713
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1714

1715
    umlDriverLock(driver);
1716
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1717 1718
    umlDriverUnlock(driver);

1719 1720 1721 1722
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1723
        virReportError(VIR_ERR_NO_DOMAIN,
1724
                       _("no domain with matching uuid '%s'"), uuidstr);
1725
        goto cleanup;
1726 1727
    }

D
Daniel P. Berrange 已提交
1728
    if (virDomainObjIsActive(vm)) {
1729
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
1730
                       _("cannot set memory of an active domain"));
1731
        goto cleanup;
1732 1733
    }

1734
    if (newmem > vm->def->mem.max_balloon) {
1735
        virReportError(VIR_ERR_INVALID_ARG, "%s",
1736
                       _("cannot set memory higher than max memory"));
1737
        goto cleanup;
1738 1739
    }

1740
    vm->def->mem.cur_balloon = newmem;
1741 1742 1743
    ret = 0;

cleanup:
1744 1745
    if (vm)
        virDomainObjUnlock(vm);
1746
    return ret;
1747 1748 1749 1750
}

static int umlDomainGetInfo(virDomainPtr dom,
                              virDomainInfoPtr info) {
1751 1752 1753 1754
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

1755
    umlDriverLock(driver);
1756
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1757 1758
    umlDriverUnlock(driver);

1759
    if (!vm) {
1760
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
1761
                       _("no domain with matching uuid"));
1762
        goto cleanup;
1763 1764
    }

J
Jiri Denemark 已提交
1765
    info->state = virDomainObjGetState(vm, NULL);
1766

D
Daniel P. Berrange 已提交
1767
    if (!virDomainObjIsActive(vm)) {
1768 1769 1770
        info->cpuTime = 0;
    } else {
        if (umlGetProcessInfo(&(info->cpuTime), vm->pid) < 0) {
1771
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
1772
                           _("cannot read cputime for domain"));
1773
            goto cleanup;
1774 1775 1776
        }
    }

1777 1778
    info->maxMem = vm->def->mem.max_balloon;
    info->memory = vm->def->mem.cur_balloon;
1779
    info->nrVirtCpu = vm->def->vcpus;
1780 1781 1782
    ret = 0;

cleanup:
1783 1784
    if (vm)
        virDomainObjUnlock(vm);
1785
    return ret;
1786 1787 1788
}


1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
static int
umlDomainGetState(virDomainPtr dom,
                  int *state,
                  int *reason,
                  unsigned int flags)
{
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(0, -1);

    umlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    umlDriverUnlock(driver);

    if (!vm) {
1806
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
1807 1808 1809 1810
                       _("no domain with matching uuid"));
        goto cleanup;
    }

J
Jiri Denemark 已提交
1811
    *state = virDomainObjGetState(vm, reason);
1812 1813 1814 1815 1816 1817 1818 1819 1820
    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}


1821
static char *umlDomainGetXMLDesc(virDomainPtr dom,
E
Eric Blake 已提交
1822 1823
                                 unsigned int flags)
{
1824 1825 1826 1827
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;

1828
    /* Flags checked by virDomainDefFormat */
E
Eric Blake 已提交
1829

1830
    umlDriverLock(driver);
1831
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1832 1833
    umlDriverUnlock(driver);

1834
    if (!vm) {
1835
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
1836
                       _("no domain with matching uuid"));
1837
        goto cleanup;
1838 1839
    }

1840
    ret = virDomainDefFormat((flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
1841 1842 1843 1844
                             vm->newDef : vm->def,
                             flags);

cleanup:
1845 1846
    if (vm)
        virDomainObjUnlock(vm);
1847
    return ret;
1848 1849 1850 1851 1852
}


static int umlListDefinedDomains(virConnectPtr conn,
                            char **const names, int nnames) {
1853
    struct uml_driver *driver = conn->privateData;
1854
    int n;
1855

1856
    umlDriverLock(driver);
1857
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
1858
    umlDriverUnlock(driver);
1859

1860
    return n;
1861 1862 1863
}

static int umlNumDefinedDomains(virConnectPtr conn) {
1864
    struct uml_driver *driver = conn->privateData;
1865
    int n;
1866

1867
    umlDriverLock(driver);
1868
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
1869
    umlDriverUnlock(driver);
1870 1871 1872 1873 1874

    return n;
}


1875
static int umlDomainStartWithFlags(virDomainPtr dom, unsigned int flags) {
1876 1877
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1878
    virDomainEventPtr event = NULL;
1879
    int ret = -1;
1880

1881
    virCheckFlags(VIR_DOMAIN_START_AUTODESTROY, -1);
1882

1883
    umlDriverLock(driver);
1884
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1885

1886
    if (!vm) {
1887
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
1888
                       _("no domain with matching uuid"));
1889
        goto cleanup;
1890 1891
    }

1892 1893
    ret = umlStartVMDaemon(dom->conn, driver, vm,
                           (flags & VIR_DOMAIN_START_AUTODESTROY));
1894
    virDomainAuditStart(vm, "booted", ret >= 0);
1895 1896 1897 1898
    if (ret == 0)
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED);
1899 1900

cleanup:
1901 1902
    if (vm)
        virDomainObjUnlock(vm);
1903 1904
    if (event)
        umlDomainEventQueue(driver, event);
1905
    umlDriverUnlock(driver);
1906
    return ret;
1907 1908
}

1909 1910 1911
static int umlDomainStart(virDomainPtr dom) {
    return umlDomainStartWithFlags(dom, 0);
}
1912 1913

static virDomainPtr umlDomainDefine(virConnectPtr conn, const char *xml) {
1914
    struct uml_driver *driver = conn->privateData;
1915
    virDomainDefPtr def;
1916
    virDomainObjPtr vm = NULL;
1917
    virDomainPtr dom = NULL;
1918

1919
    umlDriverLock(driver);
1920
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
1921
                                        1 << VIR_DOMAIN_VIRT_UML,
1922
                                        VIR_DOMAIN_XML_INACTIVE)))
1923
        goto cleanup;
1924

1925 1926 1927
    if (virDomainObjIsDuplicate(&driver->domains, def, 0) < 0)
        goto cleanup;

1928
    if (!(vm = virDomainAssignDef(driver->caps,
1929
                                  &driver->domains,
1930
                                  def, false)))
1931 1932
        goto cleanup;
    def = NULL;
1933 1934
    vm->persistent = 1;

1935
    if (virDomainSaveConfig(driver->configDir,
1936 1937 1938
                            vm->newDef ? vm->newDef : vm->def) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1939
        vm = NULL;
1940
        goto cleanup;
1941 1942 1943 1944
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1945 1946 1947

cleanup:
    virDomainDefFree(def);
1948 1949 1950
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1951 1952 1953
    return dom;
}

1954 1955 1956
static int umlDomainUndefineFlags(virDomainPtr dom,
                                  unsigned int flags)
{
1957 1958 1959
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1960

1961 1962
    virCheckFlags(0, -1);

1963
    umlDriverLock(driver);
1964
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1965
    if (!vm) {
1966
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
1967
                       _("no domain with matching uuid"));
1968
        goto cleanup;
1969 1970 1971
    }

    if (!vm->persistent) {
1972
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
1973
                       _("cannot undefine transient domain"));
1974
        goto cleanup;
1975 1976
    }

1977
    if (virDomainDeleteConfig(driver->configDir, driver->autostartDir, vm) < 0)
1978
        goto cleanup;
1979

1980 1981 1982 1983 1984 1985 1986
    if (virDomainObjIsActive(vm)) {
        vm->persistent = 0;
    } else {
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
    }

1987
    ret = 0;
1988

1989
cleanup:
1990 1991 1992
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1993
    return ret;
1994 1995 1996
}


1997 1998 1999 2000 2001
static int umlDomainUndefine(virDomainPtr dom)
{
    return umlDomainUndefineFlags(dom, 0);
}

2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
static int umlDomainAttachUmlDisk(struct uml_driver *driver,
                                  virDomainObjPtr vm,
                                  virDomainDiskDefPtr disk)
{
    int i;
    char *cmd = NULL;
    char *reply = NULL;

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, disk->dst)) {
2012
            virReportError(VIR_ERR_OPERATION_FAILED,
2013 2014 2015 2016 2017 2018
                           _("target %s already exists"), disk->dst);
            return -1;
        }
    }

    if (!disk->src) {
2019
        virReportError(VIR_ERR_INTERNAL_ERROR,
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
                       "%s", _("disk source path is missing"));
        goto error;
    }

    if (virAsprintf(&cmd, "config %s=%s", disk->dst, disk->src) < 0) {
        virReportOOMError();
        return -1;
    }

    if (umlMonitorCommand(driver, vm, cmd, &reply) < 0)
        goto error;

    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
        virReportOOMError();
        goto error;
    }

    virDomainDiskInsertPreAlloced(vm->def, disk);

    VIR_FREE(reply);
    VIR_FREE(cmd);

    return 0;

error:

    VIR_FREE(reply);
    VIR_FREE(cmd);

    return -1;
}


static int umlDomainAttachDevice(virDomainPtr dom, const char *xml)
{
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;

    umlDriverLock(driver);

    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2066
        virReportError(VIR_ERR_NO_DOMAIN,
2067 2068 2069 2070 2071
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
2072
        virReportError(VIR_ERR_OPERATION_INVALID,
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
                       "%s", _("cannot attach device on inactive domain"));
        goto cleanup;
    }

    dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                  VIR_DOMAIN_XML_INACTIVE);

    if (dev == NULL)
        goto cleanup;

    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
        if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_UML) {
            ret = umlDomainAttachUmlDisk(driver, vm, dev->data.disk);
            if (ret == 0)
                dev->data.disk = NULL;
        } else {
2089
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
2090 2091 2092 2093
                           _("disk bus '%s' cannot be hotplugged."),
                           virDomainDiskBusTypeToString(dev->data.disk->bus));
        }
    } else {
2094
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109
                       _("device type '%s' cannot be attached"),
                       virDomainDeviceTypeToString(dev->type));
        goto cleanup;
    }

cleanup:

    virDomainDeviceDefFree(dev);
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
    return ret;
}


2110 2111 2112 2113 2114 2115 2116
static int
umlDomainAttachDeviceFlags(virDomainPtr dom,
                           const char *xml,
                           unsigned int flags)
{
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG, -1);

2117
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
2118
        virReportError(VIR_ERR_OPERATION_INVALID,
2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142
                       "%s", _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    return umlDomainAttachDevice(dom, xml);
}


static int umlDomainDetachUmlDisk(struct uml_driver *driver,
                                  virDomainObjPtr vm,
                                  virDomainDeviceDefPtr dev)
{
    int i, ret = -1;
    virDomainDiskDefPtr detach = NULL;
    char *cmd;
    char *reply;

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, dev->data.disk->dst)) {
            break;
        }
    }

    if (i == vm->def->ndisks) {
2143
        virReportError(VIR_ERR_OPERATION_FAILED,
2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
                       _("disk %s not found"), dev->data.disk->dst);
        return -1;
    }

    detach = vm->def->disks[i];

    if (virAsprintf(&cmd, "remove %s", detach->dst) < 0) {
        virReportOOMError();
        return -1;
    }

    if (umlMonitorCommand(driver, vm, cmd, &reply) < 0)
        goto cleanup;

    virDomainDiskRemove(vm->def, i);

    virDomainDiskDefFree(detach);

    ret = 0;

    VIR_FREE(reply);

cleanup:
    VIR_FREE(cmd);

    return ret;
}


static int umlDomainDetachDevice(virDomainPtr dom, const char *xml) {
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;

    umlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2184
        virReportError(VIR_ERR_NO_DOMAIN,
2185 2186 2187 2188 2189
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
2190
        virReportError(VIR_ERR_OPERATION_INVALID,
2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
                       "%s", _("cannot detach device on inactive domain"));
        goto cleanup;
    }

    dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                  VIR_DOMAIN_XML_INACTIVE);
    if (dev == NULL)
        goto cleanup;

    if (dev->type == VIR_DOMAIN_DEVICE_DISK &&
        dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
        if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_UML)
            ret = umlDomainDetachUmlDisk(driver, vm, dev);
        else {
2205
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2206 2207 2208
                           _("This type of disk cannot be hot unplugged"));
        }
    } else {
2209
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
                       "%s", _("This type of device cannot be hot unplugged"));
    }

cleanup:
    virDomainDeviceDefFree(dev);
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
    return ret;
}


2222 2223 2224 2225 2226 2227 2228
static int
umlDomainDetachDeviceFlags(virDomainPtr dom,
                           const char *xml,
                           unsigned int flags)
{
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG, -1);

2229
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
2230
        virReportError(VIR_ERR_OPERATION_INVALID,
2231 2232 2233 2234 2235 2236 2237
                       "%s", _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    return umlDomainDetachDevice(dom, xml);
}

2238 2239 2240

static int umlDomainGetAutostart(virDomainPtr dom,
                            int *autostart) {
2241 2242 2243
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2244

2245
    umlDriverLock(driver);
2246
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2247

2248
    if (!vm) {
2249
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
2250
                       _("no domain with matching uuid"));
2251
        goto cleanup;
2252 2253 2254
    }

    *autostart = vm->autostart;
2255
    ret = 0;
2256

2257
cleanup:
2258 2259
    if (vm)
        virDomainObjUnlock(vm);
2260
    umlDriverUnlock(driver);
2261
    return ret;
2262 2263 2264 2265
}

static int umlDomainSetAutostart(virDomainPtr dom,
                                   int autostart) {
2266
    struct uml_driver *driver = dom->conn->privateData;
2267
    virDomainObjPtr vm;
2268 2269 2270
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

2271 2272 2273
    umlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

2274
    if (!vm) {
2275
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
2276
                       _("no domain with matching uuid"));
2277
        goto cleanup;
2278 2279 2280
    }

    if (!vm->persistent) {
2281
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
2282
                       _("cannot set autostart for transient domain"));
2283
        goto cleanup;
2284 2285 2286 2287
    }

    autostart = (autostart != 0);

2288
    if (vm->autostart != autostart) {
2289
        if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
2290
            goto cleanup;
2291
        if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
2292
            goto cleanup;
2293

2294
        if (autostart) {
2295 2296
            if (virFileMakePath(driver->autostartDir) < 0) {
                virReportSystemError(errno,
2297 2298
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
2299 2300
                goto cleanup;
            }
2301

2302
            if (symlink(configFile, autostartLink) < 0) {
2303
                virReportSystemError(errno,
2304 2305
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
2306 2307 2308 2309
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
2310
                virReportSystemError(errno,
2311 2312
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
2313 2314
                goto cleanup;
            }
2315 2316
        }

2317
        vm->autostart = autostart;
2318 2319 2320 2321 2322 2323
    }
    ret = 0;

cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
2324 2325
    if (vm)
        virDomainObjUnlock(vm);
2326
    umlDriverUnlock(driver);
2327 2328 2329 2330 2331
    return ret;
}


static int
2332 2333 2334 2335
umlDomainBlockPeek(virDomainPtr dom,
                   const char *path,
                   unsigned long long offset, size_t size,
                   void *buffer,
E
Eric Blake 已提交
2336
                   unsigned int flags)
2337
{
2338 2339
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2340 2341
    int fd = -1, ret = -1;
    const char *actual;
2342

E
Eric Blake 已提交
2343 2344
    virCheckFlags(0, -1);

2345
    umlDriverLock(driver);
2346
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2347 2348
    umlDriverUnlock(driver);

2349
    if (!vm) {
2350
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
2351
                       _("no domain with matching uuid"));
2352
        goto cleanup;
2353 2354 2355
    }

    if (!path || path[0] == '\0') {
2356
        virReportError(VIR_ERR_INVALID_ARG, "%s",
2357
                       _("NULL or empty path"));
2358
        goto cleanup;
2359 2360 2361
    }

    /* Check the path belongs to this domain. */
2362
    if (!(actual = virDomainDiskPathByName(vm->def, path))) {
2363
        virReportError(VIR_ERR_INVALID_ARG,
2364 2365
                       _("invalid path '%s'"), path);
        goto cleanup;
2366
    }
2367
    path = actual;
2368

2369 2370 2371 2372 2373 2374 2375
    /* The path is correct, now try to open it and get its size. */
    fd = open(path, O_RDONLY);
    if (fd == -1) {
        virReportSystemError(errno,
                             _("cannot open %s"), path);
        goto cleanup;
    }
2376

2377 2378 2379 2380 2381 2382 2383 2384 2385
    /* Seek and read. */
    /* NB. Because we configure with AC_SYS_LARGEFILE, off_t should
     * be 64 bits on all platforms.
     */
    if (lseek(fd, offset, SEEK_SET) == (off_t) -1 ||
        saferead(fd, buffer, size) == (ssize_t) -1) {
        virReportSystemError(errno,
                             _("cannot read %s"), path);
        goto cleanup;
2386 2387
    }

2388 2389
    ret = 0;

2390
cleanup:
2391
    VIR_FORCE_CLOSE(fd);
2392 2393
    if (vm)
        virDomainObjUnlock(vm);
2394 2395 2396 2397
    return ret;
}


2398 2399
static int
umlDomainOpenConsole(virDomainPtr dom,
2400
                     const char *dev_name,
2401 2402 2403 2404 2405 2406 2407 2408
                     virStreamPtr st,
                     unsigned int flags)
{
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    int ret = -1;
    virDomainChrDefPtr chr = NULL;
2409
    size_t i;
2410 2411 2412 2413 2414 2415 2416

    virCheckFlags(0, -1);

    umlDriverLock(driver);
    virUUIDFormat(dom->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
2417
        virReportError(VIR_ERR_NO_DOMAIN,
2418 2419 2420 2421 2422
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
2423
        virReportError(VIR_ERR_OPERATION_INVALID,
2424 2425 2426 2427
                        "%s", _("domain is not running"));
        goto cleanup;
    }

2428
    if (dev_name) {
2429 2430 2431 2432 2433 2434 2435
        for (i = 0 ; i < vm->def->nconsoles ; i++) {
            if (vm->def->consoles[i]->info.alias &&
                STREQ(vm->def->consoles[i]->info.alias, dev_name)) {
                chr = vm->def->consoles[i];
                break;
            }
        }
2436
    } else {
2437 2438
        if (vm->def->nconsoles)
            chr = vm->def->consoles[0];
2439 2440 2441 2442 2443
        else if (vm->def->nserials)
            chr = vm->def->serials[0];
    }

    if (!chr) {
2444
        virReportError(VIR_ERR_INTERNAL_ERROR,
2445 2446
                       _("cannot find console device '%s'"),
                       dev_name ? dev_name : _("default"));
2447 2448 2449
        goto cleanup;
    }

2450
    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
2451
        virReportError(VIR_ERR_INTERNAL_ERROR,
2452
                        _("character device %s is not using a PTY"), dev_name);
2453 2454 2455
        goto cleanup;
    }

2456
    if (virFDStreamOpenFile(st, chr->source.data.file.path,
E
Eric Blake 已提交
2457
                            0, 0, O_RDWR) < 0)
2458 2459 2460 2461 2462 2463 2464 2465 2466 2467
        goto cleanup;

    ret = 0;
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
    return ret;
}

2468

2469 2470 2471 2472 2473 2474 2475 2476 2477 2478
static int
umlDomainEventRegister(virConnectPtr conn,
                       virConnectDomainEventCallback callback,
                       void *opaque,
                       virFreeCallback freecb)
{
    struct uml_driver *driver = conn->privateData;
    int ret;

    umlDriverLock(driver);
2479 2480 2481
    ret = virDomainEventStateRegister(conn,
                                      driver->domainEventState,
                                      callback, opaque, freecb);
2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514
    umlDriverUnlock(driver);

    return ret;
}

static int
umlDomainEventDeregister(virConnectPtr conn,
                         virConnectDomainEventCallback callback)
{
    struct uml_driver *driver = conn->privateData;
    int ret;

    umlDriverLock(driver);
    ret = virDomainEventStateDeregister(conn,
                                        driver->domainEventState,
                                        callback);
    umlDriverUnlock(driver);

    return ret;
}

static int
umlDomainEventRegisterAny(virConnectPtr conn,
                          virDomainPtr dom,
                          int eventID,
                          virConnectDomainEventGenericCallback callback,
                          void *opaque,
                          virFreeCallback freecb)
{
    struct uml_driver *driver = conn->privateData;
    int ret;

    umlDriverLock(driver);
2515 2516 2517 2518
    if (virDomainEventStateRegisterID(conn,
                                      driver->domainEventState,
                                      dom, eventID,
                                      callback, opaque, freecb, &ret) < 0)
2519
        ret = -1;
2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533
    umlDriverUnlock(driver);

    return ret;
}


static int
umlDomainEventDeregisterAny(virConnectPtr conn,
                            int callbackID)
{
    struct uml_driver *driver = conn->privateData;
    int ret;

    umlDriverLock(driver);
2534 2535 2536
    ret = virDomainEventStateDeregisterID(conn,
                                          driver->domainEventState,
                                          callbackID);
2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549
    umlDriverUnlock(driver);

    return ret;
}


/* driver must be locked before calling */
static void umlDomainEventQueue(struct uml_driver *driver,
                                virDomainEventPtr event)
{
    virDomainEventStateQueue(driver->domainEventState, event);
}

2550 2551 2552 2553 2554 2555 2556
static int umlListAllDomains(virConnectPtr conn,
                             virDomainPtr **domains,
                             unsigned int flags)
{
    struct uml_driver *driver = conn->privateData;
    int ret = -1;

O
Osier Yang 已提交
2557
    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);
2558 2559 2560 2561 2562 2563 2564 2565

    umlDriverLock(driver);
    ret = virDomainList(conn, driver->domains.objs, domains, flags);
    umlDriverUnlock(driver);

    return ret;
}

2566 2567


2568
static virDriver umlDriver = {
2569 2570
    .no = VIR_DRV_UML,
    .name = "UML",
2571 2572 2573 2574 2575 2576 2577 2578 2579
    .open = umlOpen, /* 0.5.0 */
    .close = umlClose, /* 0.5.0 */
    .type = umlGetType, /* 0.5.0 */
    .version = umlGetVersion, /* 0.5.0 */
    .getHostname = virGetHostname, /* 0.5.0 */
    .nodeGetInfo = nodeGetInfo, /* 0.5.0 */
    .getCapabilities = umlGetCapabilities, /* 0.5.0 */
    .listDomains = umlListDomains, /* 0.5.0 */
    .numOfDomains = umlNumDomains, /* 0.5.0 */
2580
    .listAllDomains = umlListAllDomains, /* 0.9.13 */
2581 2582 2583 2584 2585
    .domainCreateXML = umlDomainCreate, /* 0.5.0 */
    .domainLookupByID = umlDomainLookupByID, /* 0.5.0 */
    .domainLookupByUUID = umlDomainLookupByUUID, /* 0.5.0 */
    .domainLookupByName = umlDomainLookupByName, /* 0.5.0 */
    .domainShutdown = umlDomainShutdown, /* 0.5.0 */
2586
    .domainShutdownFlags = umlDomainShutdownFlags, /* 0.9.10 */
2587
    .domainDestroy = umlDomainDestroy, /* 0.5.0 */
2588
    .domainDestroyFlags = umlDomainDestroyFlags, /* 0.9.4 */
2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601
    .domainGetOSType = umlDomainGetOSType, /* 0.5.0 */
    .domainGetMaxMemory = umlDomainGetMaxMemory, /* 0.5.0 */
    .domainSetMaxMemory = umlDomainSetMaxMemory, /* 0.5.0 */
    .domainSetMemory = umlDomainSetMemory, /* 0.5.0 */
    .domainGetInfo = umlDomainGetInfo, /* 0.5.0 */
    .domainGetState = umlDomainGetState, /* 0.9.2 */
    .domainGetXMLDesc = umlDomainGetXMLDesc, /* 0.5.0 */
    .listDefinedDomains = umlListDefinedDomains, /* 0.5.0 */
    .numOfDefinedDomains = umlNumDefinedDomains, /* 0.5.0 */
    .domainCreate = umlDomainStart, /* 0.5.0 */
    .domainCreateWithFlags = umlDomainStartWithFlags, /* 0.8.2 */
    .domainDefineXML = umlDomainDefine, /* 0.5.0 */
    .domainUndefine = umlDomainUndefine, /* 0.5.0 */
2602
    .domainUndefineFlags = umlDomainUndefineFlags, /* 0.9.4 */
2603 2604 2605 2606 2607 2608 2609
    .domainAttachDevice = umlDomainAttachDevice, /* 0.8.4 */
    .domainAttachDeviceFlags = umlDomainAttachDeviceFlags, /* 0.8.4 */
    .domainDetachDevice = umlDomainDetachDevice, /* 0.8.4 */
    .domainDetachDeviceFlags = umlDomainDetachDeviceFlags, /* 0.8.4 */
    .domainGetAutostart = umlDomainGetAutostart, /* 0.5.0 */
    .domainSetAutostart = umlDomainSetAutostart, /* 0.5.0 */
    .domainBlockPeek = umlDomainBlockPeek, /* 0.5.0 */
2610
    .nodeGetCPUStats = nodeGetCPUStats, /* 0.9.3 */
2611
    .nodeGetMemoryStats = nodeGetMemoryStats, /* 0.9.3 */
2612 2613
    .nodeGetCellsFreeMemory = nodeGetCellsFreeMemory, /* 0.5.0 */
    .nodeGetFreeMemory = nodeGetFreeMemory, /* 0.5.0 */
2614 2615
    .domainEventRegister = umlDomainEventRegister, /* 0.9.4 */
    .domainEventDeregister = umlDomainEventDeregister, /* 0.9.4 */
2616 2617 2618 2619 2620
    .isEncrypted = umlIsEncrypted, /* 0.7.3 */
    .isSecure = umlIsSecure, /* 0.7.3 */
    .domainIsActive = umlDomainIsActive, /* 0.7.3 */
    .domainIsPersistent = umlDomainIsPersistent, /* 0.7.3 */
    .domainIsUpdated = umlDomainIsUpdated, /* 0.8.6 */
2621 2622
    .domainEventRegisterAny = umlDomainEventRegisterAny, /* 0.9.4 */
    .domainEventDeregisterAny = umlDomainEventDeregisterAny, /* 0.9.4 */
2623
    .domainOpenConsole = umlDomainOpenConsole, /* 0.8.6 */
2624
    .isAlive = umlIsAlive, /* 0.9.8 */
2625
    .nodeSuspendForDuration = nodeSuspendForDuration, /* 0.9.8 */
2626 2627
    .nodeGetMemoryParameters = nodeGetMemoryParameters, /* 0.10.2 */
    .nodeSetMemoryParameters = nodeSetMemoryParameters, /* 0.10.2 */
2628 2629 2630
};

static virStateDriver umlStateDriver = {
2631
    .name = "UML",
2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642
    .initialize = umlStartup,
    .cleanup = umlShutdown,
    .reload = umlReload,
    .active = umlActive,
};

int umlRegister(void) {
    virRegisterDriver(&umlDriver);
    virRegisterStateDriver(&umlStateDriver);
    return 0;
}