uml_driver.c 71.9 KB
Newer Older
1 2 3
/*
 * uml_driver.c: core driver methods for managing UML guests
 *
4
 * Copyright (C) 2006-2011 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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 45
 * 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
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#include <sys/types.h>
#include <sys/poll.h>
#include <dirent.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>
46
#include <sys/un.h>
47 48 49 50 51 52 53 54 55 56 57

#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"
58
#include "domain_audit.h"
59
#include "datatypes.h"
60
#include "logging.h"
61
#include "domain_nwfilter.h"
E
Eric Blake 已提交
62
#include "virfile.h"
63
#include "fdstream.h"
64
#include "configmake.h"
65

66 67
#define VIR_FROM_THIS VIR_FROM_UML

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

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

78 79 80 81 82 83 84 85 86 87
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);

88

89 90
static int umlShutdown(void);

91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
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);
}


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

121

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

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

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


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

static struct uml_driver *uml_driver = NULL;

147 148 149 150 151 152
struct umlAutostartData {
    struct uml_driver *driver;
    virConnectPtr conn;
};

static void
153
umlAutostartDomain(void *payload, const void *name ATTRIBUTE_UNUSED, void *opaque)
154 155 156 157 158 159
{
    virDomainObjPtr vm = payload;
    const struct umlAutostartData *data = opaque;

    virDomainObjLock(vm);
    if (vm->autostart &&
D
Daniel P. Berrange 已提交
160
        !virDomainObjIsActive(vm)) {
161
        int ret;
162
        virResetLastError();
163
        ret = umlStartVMDaemon(data->conn, data->driver, vm, false);
164 165
        virDomainAuditStart(vm, "booted", ret >= 0);
        if (ret < 0) {
166 167
            virErrorPtr err = virGetLastError();
            VIR_ERROR(_("Failed to autostart VM '%s': %s"),
168
                      vm->def->name, err ? err->message : _("unknown error"));
169 170 171 172 173 174 175
        } else {
            virDomainEventPtr event =
                virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED);
            if (event)
                umlDomainEventQueue(data->driver, event);
176 177 178 179
        }
    }
    virDomainObjUnlock(vm);
}
180 181 182

static void
umlAutostartConfigs(struct uml_driver *driver) {
183 184 185 186 187
    /* 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
     */
188 189 190
    virConnectPtr conn = virConnectOpen(driver->privileged ?
                                        "uml:///system" :
                                        "uml:///session");
191
    /* Ignoring NULL conn which is mostly harmless here */
192

193 194
    struct umlAutostartData data = { driver, conn };

195
    umlDriverLock(driver);
196
    virHashForEach(driver->domains.objs, umlAutostartDomain, &data);
197
    umlDriverUnlock(driver);
198

199 200
    if (conn)
        virConnectClose(conn);
201 202 203 204
}


static int
205
umlIdentifyOneChrPTY(struct uml_driver *driver,
206 207 208 209 210 211 212
                     virDomainObjPtr dom,
                     virDomainChrDefPtr def,
                     const char *dev)
{
    char *cmd;
    char *res = NULL;
    int retries = 0;
213
    if (virAsprintf(&cmd, "config %s%d", dev, def->target.port) < 0) {
214
        virReportOOMError();
215 216 217
        return -1;
    }
requery:
218
    if (umlMonitorCommand(driver, dom, cmd, &res) < 0)
219
        return -1;
220

221
    if (res && STRPREFIX(res, "pts:")) {
222 223
        VIR_FREE(def->source.data.file.path);
        if ((def->source.data.file.path = strdup(res + 4)) == NULL) {
224
            virReportOOMError();
225 226 227 228
            VIR_FREE(res);
            VIR_FREE(cmd);
            return -1;
        }
229
    } else if (!res || STRPREFIX(res, "pts")) {
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
        /* 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
246
umlIdentifyChrPTY(struct uml_driver *driver,
247 248 249 250 251
                  virDomainObjPtr dom)
{
    int i;

    if (dom->def->console &&
252
        dom->def->console->source.type == VIR_DOMAIN_CHR_TYPE_PTY)
253
        if (umlIdentifyOneChrPTY(driver, dom,
254 255 256 257
                                 dom->def->console, "con") < 0)
            return -1;

    for (i = 0 ; i < dom->def->nserials; i++)
258
        if (dom->def->serials[i]->source.type == VIR_DOMAIN_CHR_TYPE_PTY &&
259
            umlIdentifyOneChrPTY(driver, dom,
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
                                 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;
278
    virDomainEventPtr event = NULL;
279

280
    umlDriverLock(driver);
281
    if (watch != driver->inotifyWatch)
282
        goto cleanup;
283 284 285 286 287 288

reread:
    got = read(fd, buf, sizeof(buf));
    if (got == -1) {
        if (errno == EINTR)
            goto reread;
289
        goto cleanup;
290 291 292 293 294
    }

    tmp = buf;
    while (got) {
        if (got < sizeof(struct inotify_event))
295
            goto cleanup; /* bad */
296 297 298 299 300 301

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

        if (got < e->len)
302
            goto cleanup;
303 304 305 306 307 308 309 310 311 312 313 314 315

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

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

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

        if (!dom) {
            continue;
        }

        if (e->mask & IN_DELETE) {
316
            VIR_DEBUG("Got inotify domain shutdown '%s'", name);
D
Daniel P. Berrange 已提交
317
            if (!virDomainObjIsActive(dom)) {
318
                virDomainObjUnlock(dom);
319 320 321
                continue;
            }

322
            umlShutdownVMDaemon(driver, dom, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
323
            virDomainAuditStop(dom, "shutdown");
324 325 326
            event = virDomainEventNewFromObj(dom,
                                             VIR_DOMAIN_EVENT_STOPPED,
                                             VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN);
327 328 329 330 331
            if (!dom->persistent) {
                virDomainRemoveInactive(&driver->domains,
                                        dom);
                dom = NULL;
            }
332
        } else if (e->mask & (IN_CREATE | IN_MODIFY)) {
333
            VIR_DEBUG("Got inotify domain startup '%s'", name);
D
Daniel P. Berrange 已提交
334
            if (virDomainObjIsActive(dom)) {
335
                virDomainObjUnlock(dom);
336 337 338
                continue;
            }

339
            if (umlReadPidFile(driver, dom) < 0) {
340
                virDomainObjUnlock(dom);
341 342 343 344
                continue;
            }

            dom->def->id = driver->nextvmid++;
J
Jiri Denemark 已提交
345 346
            virDomainObjSetState(dom, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_BOOTED);
347

348
            if (umlOpenMonitor(driver, dom) < 0) {
349
                VIR_WARN("Could not open monitor for new domain");
350
                umlShutdownVMDaemon(driver, dom,
J
Jiri Denemark 已提交
351
                                    VIR_DOMAIN_SHUTOFF_FAILED);
352
                virDomainAuditStop(dom, "failed");
353 354 355
                event = virDomainEventNewFromObj(dom,
                                                 VIR_DOMAIN_EVENT_STOPPED,
                                                 VIR_DOMAIN_EVENT_STOPPED_FAILED);
356 357 358 359 360
                if (!dom->persistent) {
                    virDomainRemoveInactive(&driver->domains,
                                            dom);
                    dom = NULL;
                }
361
            } else if (umlIdentifyChrPTY(driver, dom) < 0) {
362
                VIR_WARN("Could not identify character devices for new domain");
363
                umlShutdownVMDaemon(driver, dom,
J
Jiri Denemark 已提交
364
                                    VIR_DOMAIN_SHUTOFF_FAILED);
365
                virDomainAuditStop(dom, "failed");
366 367 368
                event = virDomainEventNewFromObj(dom,
                                                 VIR_DOMAIN_EVENT_STOPPED,
                                                 VIR_DOMAIN_EVENT_STOPPED_FAILED);
369 370 371 372 373
                if (!dom->persistent) {
                    virDomainRemoveInactive(&driver->domains,
                                            dom);
                    dom = NULL;
                }
374
            }
375
        }
376 377
        if (dom)
            virDomainObjUnlock(dom);
378
    }
379 380

cleanup:
381 382
    if (event)
        umlDomainEventQueue(driver, event);
383
    umlDriverUnlock(driver);
384 385 386 387 388 389 390 391
}

/**
 * umlStartup:
 *
 * Initialization function for the Uml daemon
 */
static int
392 393
umlStartup(int privileged)
{
394 395
    uid_t uid = geteuid();
    char *base = NULL;
396
    char *userdir = NULL;
397 398 399 400

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

401 402
    uml_driver->privileged = privileged;

403 404 405 406
    if (virMutexInit(&uml_driver->lock) < 0) {
        VIR_FREE(uml_driver);
        return -1;
    }
407 408
    umlDriverLock(uml_driver);

409 410
    /* Don't have a dom0 so start from 1 */
    uml_driver->nextvmid = 1;
411
    uml_driver->inotifyWatch = -1;
412

413 414 415
    if (virDomainObjListInit(&uml_driver->domains) < 0)
        goto error;

416 417 418 419 420 421 422
    uml_driver->domainEventState = virDomainEventStateNew(umlDomainEventFlush,
                                                          uml_driver,
                                                          NULL,
                                                          true);
    if (!uml_driver->domainEventState)
        goto error;

423
    userdir = virGetUserDirectory(uid);
424
    if (!userdir)
425
        goto error;
426

427
    if (privileged) {
428
        if (virAsprintf(&uml_driver->logDir,
429
                        "%s/log/libvirt/uml", LOCALSTATEDIR) == -1)
430 431
            goto out_of_memory;

432
        if ((base = strdup (SYSCONFDIR "/libvirt")) == NULL)
433
            goto out_of_memory;
434 435

        if (virAsprintf(&uml_driver->monitorDir,
436
                        "%s/run/libvirt/uml-guest", LOCALSTATEDIR) == -1)
437
            goto out_of_memory;
438
    } else {
439

440
        if (virAsprintf(&uml_driver->logDir,
441
                        "%s/.libvirt/uml/log", userdir) == -1)
442 443
            goto out_of_memory;

444
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1)
445 446
            goto out_of_memory;

447 448 449 450
        if (virAsprintf(&uml_driver->monitorDir,
                        "%s/.uml", userdir) == -1)
            goto out_of_memory;
    }
451 452 453 454

    /* Configuration paths are either ~/.libvirt/uml/... (session) or
     * /etc/libvirt/uml/... (system).
     */
455
    if (virAsprintf(&uml_driver->configDir, "%s/uml", base) == -1)
456 457
        goto out_of_memory;

458
    if (virAsprintf(&uml_driver->autostartDir, "%s/uml/autostart", base) == -1)
459 460 461 462 463 464 465
        goto out_of_memory;

    VIR_FREE(base);

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

466 467
    uml_driver->caps->privateDataAllocFunc = umlDomainObjPrivateAlloc;
    uml_driver->caps->privateDataFreeFunc = umlDomainObjPrivateFree;
468 469

    if ((uml_driver->inotifyFD = inotify_init()) < 0) {
470
        VIR_ERROR(_("cannot initialize inotify"));
471
        goto error;
472 473
    }

474
    if (virFileMakePath(uml_driver->monitorDir) < 0) {
475
        char ebuf[1024];
D
Daniel Veillard 已提交
476
        VIR_ERROR(_("Failed to create monitor directory %s: %s"),
477
               uml_driver->monitorDir, virStrerror(errno, ebuf, sizeof ebuf));
478
        goto error;
479 480
    }

481
    VIR_INFO("Adding inotify watch on %s", uml_driver->monitorDir);
482 483 484
    if (inotify_add_watch(uml_driver->inotifyFD,
                          uml_driver->monitorDir,
                          IN_CREATE | IN_MODIFY | IN_DELETE) < 0) {
485
        goto error;
486 487
    }

488 489
    if ((uml_driver->inotifyWatch =
         virEventAddHandle(uml_driver->inotifyFD, POLLIN,
490 491
                           umlInotifyEvent, uml_driver, NULL)) < 0)
        goto error;
492

493 494 495
    if (umlProcessAutoDestroyInit(uml_driver) < 0)
        goto error;

496
    if (virDomainLoadAllConfigs(uml_driver->caps,
497 498 499
                                &uml_driver->domains,
                                uml_driver->configDir,
                                uml_driver->autostartDir,
M
Matthias Bolte 已提交
500 501
                                0, 1 << VIR_DOMAIN_VIRT_UML,
                                NULL, NULL) < 0)
502 503
        goto error;

504 505
    umlDriverUnlock(uml_driver);

506 507
    umlAutostartConfigs(uml_driver);

508 509
    VIR_FREE(userdir);

510 511
    return 0;

512
out_of_memory:
513
    VIR_ERROR(_("umlStartup: out of memory"));
514 515

error:
516
    VIR_FREE(userdir);
517
    VIR_FREE(base);
518 519
    umlDriverUnlock(uml_driver);
    umlShutdown();
520 521 522
    return -1;
}

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
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);
    }
}


538 539 540 541 542 543 544 545 546 547 548
/**
 * 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;

549
    umlDriverLock(uml_driver);
550
    virDomainLoadAllConfigs(uml_driver->caps,
551 552 553
                            &uml_driver->domains,
                            uml_driver->configDir,
                            uml_driver->autostartDir,
M
Matthias Bolte 已提交
554
                            0, 1 << VIR_DOMAIN_VIRT_UML,
555 556
                            umlNotifyLoadDomain, uml_driver);
    umlDriverUnlock(uml_driver);
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572

    umlAutostartConfigs(uml_driver);

    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) {
573
    int active = 0;
574 575 576 577

    if (!uml_driver)
        return 0;

578
    umlDriverLock(uml_driver);
579
    active = virDomainObjListNumOfDomains(&uml_driver->domains, 1);
580
    umlDriverUnlock(uml_driver);
581

582
    return active;
583 584
}

585
static void
586
umlShutdownOneVM(void *payload, const void *name ATTRIBUTE_UNUSED, void *opaque)
587 588 589 590 591
{
    virDomainObjPtr dom = payload;
    struct uml_driver *driver = opaque;

    virDomainObjLock(dom);
592
    if (virDomainObjIsActive(dom)) {
593
        umlShutdownVMDaemon(driver, dom, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
594 595
        virDomainAuditStop(dom, "shutdown");
    }
596 597 598
    virDomainObjUnlock(dom);
}

599 600 601 602 603 604 605 606 607 608
/**
 * umlShutdown:
 *
 * Shutdown the Uml daemon, it will stop all active domains and networks
 */
static int
umlShutdown(void) {
    if (!uml_driver)
        return -1;

609
    umlDriverLock(uml_driver);
610 611
    if (uml_driver->inotifyWatch != -1)
        virEventRemoveHandle(uml_driver->inotifyWatch);
612
    VIR_FORCE_CLOSE(uml_driver->inotifyFD);
613 614
    virCapabilitiesFree(uml_driver->caps);

615 616 617
    /* shutdown active VMs
     * XXX allow them to stay around & reconnect */
    virHashForEach(uml_driver->domains.objs, umlShutdownOneVM, uml_driver);
618

619
    virDomainObjListDeinit(&uml_driver->domains);
620

621 622
    virDomainEventStateFree(uml_driver->domainEventState);

623 624 625 626 627
    VIR_FREE(uml_driver->logDir);
    VIR_FREE(uml_driver->configDir);
    VIR_FREE(uml_driver->autostartDir);
    VIR_FREE(uml_driver->monitorDir);

628 629
    umlProcessAutoDestroyShutdown(uml_driver);

630 631 632
    if (uml_driver->brctl)
        brShutdown(uml_driver->brctl);

633
    umlDriverUnlock(uml_driver);
634
    virMutexDestroy(&uml_driver->lock);
635 636 637 638 639 640
    VIR_FREE(uml_driver);

    return 0;
}


641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 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
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;
}


739
static int umlReadPidFile(struct uml_driver *driver,
740 741 742 743 744 745 746 747
                          virDomainObjPtr vm)
{
    int rc = -1;
    FILE *file;
    char *pidfile = NULL;
    int retries = 0;

    vm->pid = -1;
748 749
    if (virAsprintf(&pidfile, "%s/%s/pid",
                    driver->monitorDir, vm->def->name) < 0) {
750
        virReportOOMError();
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
        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;
766
        VIR_FORCE_FCLOSE(file);
767 768 769
        goto cleanup;
    }

770
    if (VIR_FCLOSE(file) < 0)
771 772 773 774 775 776
        goto cleanup;

    rc = 0;

 cleanup:
    if (rc != 0)
777
        virReportSystemError(errno,
778 779
                             _("failed to read pid: %s"),
                             pidfile);
780 781 782 783
    VIR_FREE(pidfile);
    return rc;
}

784
static int umlMonitorAddress(const struct uml_driver *driver,
785 786 787
                             virDomainObjPtr vm,
                             struct sockaddr_un *addr) {
    char *sockname;
C
Chris Lalancette 已提交
788
    int retval = 0;
789

790 791
    if (virAsprintf(&sockname, "%s/%s/mconsole",
                    driver->monitorDir, vm->def->name) < 0) {
792
        virReportOOMError();
793 794 795 796 797
        return -1;
    }

    memset(addr, 0, sizeof *addr);
    addr->sun_family = AF_UNIX;
C
Chris Lalancette 已提交
798
    if (virStrcpyStatic(addr->sun_path, sockname) == NULL) {
799
        umlReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
800 801 802
                       _("Unix path %s too long for destination"), sockname);
        retval = -1;
    }
803
    VIR_FREE(sockname);
C
Chris Lalancette 已提交
804
    return retval;
805 806
}

807
static int umlOpenMonitor(struct uml_driver *driver,
808 809 810 811
                          virDomainObjPtr vm) {
    struct sockaddr_un addr;
    struct stat sb;
    int retries = 0;
812
    umlDomainObjPrivatePtr priv = vm->privateData;
813

814
    if (umlMonitorAddress(driver, vm, &addr) < 0)
815 816
        return -1;

817
    VIR_DEBUG("Dest address for monitor is '%s'", addr.sun_path);
818 819 820
restat:
    if (stat(addr.sun_path, &sb) < 0) {
        if (errno == ENOENT &&
821
            retries++ < 50) {
822 823 824 825 826 827
            usleep(1000 * 100);
            goto restat;
        }
        return -1;
    }

828
    if ((priv->monitor = socket(PF_UNIX, SOCK_DGRAM, 0)) < 0) {
829
        virReportSystemError(errno,
830
                             "%s", _("cannot open socket"));
831 832 833 834
        return -1;
    }

    memset(addr.sun_path, 0, sizeof addr.sun_path);
E
Eric Blake 已提交
835 836
    snprintf(addr.sun_path + 1, sizeof(addr.sun_path) - 1,
             "libvirt-uml-%u", vm->pid);
837
    VIR_DEBUG("Reply address for monitor is '%s'", addr.sun_path+1);
838
    if (bind(priv->monitor, (struct sockaddr *)&addr, sizeof addr) < 0) {
839
        virReportSystemError(errno,
840
                             "%s", _("cannot bind socket"));
841
        VIR_FORCE_CLOSE(priv->monitor);
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
        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];
};


868
static int umlMonitorCommand(const struct uml_driver *driver,
869 870 871 872 873 874 875 876 877 878
                             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;
879
    umlDomainObjPrivatePtr priv = vm->privateData;
880

881 882
    VIR_DEBUG("Run command '%s'", cmd);

883 884
    *reply = NULL;

885
    if (umlMonitorAddress(driver, vm, &addr) < 0)
886 887 888 889 890 891 892
        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)) {
893
        virReportSystemError(EINVAL,
894 895
                             _("cannot send too long command %s (%d bytes)"),
                             cmd, req.length);
896 897
        return -1;
    }
C
Chris Lalancette 已提交
898
    if (virStrcpyStatic(req.data, cmd) == NULL) {
899
        umlReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
900 901 902
                       _("Command %s too long for destination"), cmd);
        return -1;
    }
903

904
    if (sendto(priv->monitor, &req, sizeof req, 0,
905
               (struct sockaddr *)&addr, sizeof addr) != (sizeof req)) {
906
        virReportSystemError(errno,
907 908
                             _("cannot send command %s"),
                             cmd);
909 910 911 912
        return -1;
    }

    do {
E
Eric Blake 已提交
913
        ssize_t nbytes;
914
        addrlen = sizeof(addr);
E
Eric Blake 已提交
915
        nbytes = recvfrom(priv->monitor, &res, sizeof res, 0,
916
                          (struct sockaddr *)&addr, &addrlen);
E
Eric Blake 已提交
917 918 919
        if (nbytes < 0) {
            if (errno == EAGAIN || errno == EINTR)
                continue;
920
            virReportSystemError(errno, _("cannot read reply %s"), cmd);
921 922
            goto error;
        }
923 924 925
        /* 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) {
926 927 928
            virReportSystemError(0, _("incomplete reply %s"), cmd);
            goto error;
        }
929 930

        if (VIR_REALLOC_N(retdata, retlen + res.length) < 0) {
931
            virReportOOMError();
932 933 934 935 936 937 938 939 940 941 942
            goto error;
        }
        memcpy(retdata + retlen, res.data, res.length);
        retlen += res.length - 1;
        retdata[retlen] = '\0';

        if (res.error)
            ret = -1;

    } while (res.extra);

943 944
    VIR_DEBUG("Command reply is '%s'", NULLSTR(retdata));

945 946 947 948
    if (ret < 0)
        VIR_FREE(retdata);
    else
        *reply = retdata;
949 950 951 952 953 954 955 956 957

    return ret;

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


958
static int umlCleanupTapDevices(virDomainObjPtr vm) {
959 960 961 962
    int i;
    int err;
    int ret = 0;
    brControl *brctl = NULL;
963
    VIR_ERROR(_("Cleanup tap"));
964 965 966 967 968 969 970 971 972 973
    if (brInit(&brctl) < 0)
        return -1;

    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;

974
        VIR_ERROR(_("Cleanup '%s'"), def->ifname);
975 976
        err = brDeleteTap(brctl, def->ifname);
        if (err) {
977
            VIR_ERROR(_("Cleanup failed %d"), err);
978 979 980
            ret = -1;
        }
    }
981
    VIR_ERROR(_("Cleanup tap done"));
982 983 984 985
    brShutdown(brctl);
    return ret;
}

986 987
static int umlStartVMDaemon(virConnectPtr conn,
                            struct uml_driver *driver,
988 989
                            virDomainObjPtr vm,
                            bool autoDestroy) {
D
Daniel P. Berrange 已提交
990
    int ret;
991 992
    char *logfile;
    int logfd = -1;
993
    umlDomainObjPrivatePtr priv = vm->privateData;
D
Daniel P. Berrange 已提交
994
    virCommandPtr cmd = NULL;
995

D
Daniel P. Berrange 已提交
996
    if (virDomainObjIsActive(vm)) {
997
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
998
                       _("VM is already active"));
999 1000 1001 1002
        return -1;
    }

    if (!vm->def->os.kernel) {
1003 1004
        umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("no kernel specified"));
1005 1006 1007 1008 1009 1010
        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 已提交
1011
    if (!virFileIsExecutable(vm->def->os.kernel)) {
1012
        virReportSystemError(errno,
1013 1014
                             _("Cannot find UML kernel %s"),
                             vm->def->os.kernel);
1015 1016 1017
        return -1;
    }

1018
    if (virFileMakePath(driver->logDir) < 0) {
1019
        virReportSystemError(errno,
1020 1021
                             _("cannot create log directory %s"),
                             driver->logDir);
1022 1023 1024
        return -1;
    }

1025 1026
    if (virAsprintf(&logfile, "%s/%s.log",
                    driver->logDir, vm->def->name) < 0) {
1027
        virReportOOMError();
1028 1029 1030 1031 1032
        return -1;
    }

    if ((logfd = open(logfile, O_CREAT | O_TRUNC | O_WRONLY,
                      S_IRUSR | S_IWUSR)) < 0) {
1033
        virReportSystemError(errno,
1034 1035
                             _("failed to create logfile %s"),
                             logfile);
1036 1037 1038 1039 1040
        VIR_FREE(logfile);
        return -1;
    }
    VIR_FREE(logfile);

E
Eric Blake 已提交
1041 1042 1043
    if (virSetCloseExec(logfd) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to set VM logfile close-on-exec flag"));
1044
        VIR_FORCE_CLOSE(logfd);
1045 1046 1047
        return -1;
    }

D
Daniel P. Berrange 已提交
1048
    if (!(cmd = umlBuildCommandLine(conn, driver, vm))) {
1049
        VIR_FORCE_CLOSE(logfd);
1050
        virDomainConfVMNWFilterTeardown(vm);
1051
        umlCleanupTapDevices(vm);
1052 1053 1054
        return -1;
    }

D
Daniel P. Berrange 已提交
1055
    virCommandWriteArgLog(cmd, logfd);
1056

1057
    priv->monitor = -1;
1058

D
Daniel P. Berrange 已提交
1059 1060 1061 1062 1063 1064
    virCommandClearCaps(cmd);
    virCommandSetOutputFD(cmd, &logfd);
    virCommandSetErrorFD(cmd, &logfd);
    virCommandDaemonize(cmd);

    ret = virCommandRun(cmd, NULL);
1065
    VIR_FORCE_CLOSE(logfd);
1066 1067
    if (ret < 0)
        goto cleanup;
1068

1069 1070 1071 1072
    if (autoDestroy &&
        umlProcessAutoDestroyAdd(driver, vm, conn) < 0)
        goto cleanup;

1073
    ret = virDomainObjSetDefTransient(driver->caps, vm, false);
1074
cleanup:
D
Daniel P. Berrange 已提交
1075
    virCommandFree(cmd);
1076

1077 1078
    if (ret < 0) {
        virDomainConfVMNWFilterTeardown(vm);
1079
        umlCleanupTapDevices(vm);
1080 1081
    }

1082 1083
    /* NB we don't mark it running here - we do that async
       with inotify */
1084 1085 1086
    /* XXX what if someone else tries to start it again
       before we get the inotification ? Sounds like
       trouble.... */
1087
    /* XXX this is bad for events too. must fix this better */
1088 1089 1090 1091

    return ret;
}

1092
static void umlShutdownVMDaemon(struct uml_driver *driver,
J
Jiri Denemark 已提交
1093 1094
                                virDomainObjPtr vm,
                                virDomainShutoffReason reason)
1095 1096
{
    int ret;
1097 1098
    umlDomainObjPrivatePtr priv = vm->privateData;

D
Daniel P. Berrange 已提交
1099
    if (!virDomainObjIsActive(vm))
1100 1101
        return;

1102
    virKillProcess(vm->pid, SIGTERM);
1103

1104
    VIR_FORCE_CLOSE(priv->monitor);
1105 1106

    if ((ret = waitpid(vm->pid, NULL, 0)) != vm->pid) {
1107
        VIR_WARN("Got unexpected pid %d != %d",
1108 1109 1110 1111 1112
               ret, vm->pid);
    }

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

1115
    virDomainConfVMNWFilterTeardown(vm);
1116 1117 1118 1119
    umlCleanupTapDevices(vm);

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

1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
    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 已提交
1132 1133 1134 1135
                                unsigned int flags)
{
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

1136 1137 1138
    if (conn->uri == NULL) {
        if (uml_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;
1139

1140
        conn->uri = xmlParseURI(uml_driver->privileged ?
1141 1142 1143
                                "uml:///system" :
                                "uml:///session");
        if (!conn->uri) {
1144
            virReportOOMError();
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
            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;
1155 1156


1157
        /* Check path and tell them correct path if they made a mistake */
1158
        if (uml_driver->privileged) {
1159
            if (STRNEQ (conn->uri->path, "/system") &&
1160
                STRNEQ (conn->uri->path, "/session")) {
1161
                umlReportError(VIR_ERR_INTERNAL_ERROR,
1162 1163 1164 1165 1166 1167
                               _("unexpected UML URI path '%s', try uml:///system"),
                               conn->uri->path);
                return VIR_DRV_OPEN_ERROR;
            }
        } else {
            if (STRNEQ (conn->uri->path, "/session")) {
1168
                umlReportError(VIR_ERR_INTERNAL_ERROR,
1169 1170 1171 1172
                               _("unexpected UML URI path '%s', try uml:///session"),
                               conn->uri->path);
                return VIR_DRV_OPEN_ERROR;
            }
1173
        }
1174 1175 1176

        /* URI was good, but driver isn't active */
        if (uml_driver == NULL) {
1177
            umlReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1178
                           _("uml state driver is not active"));
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
            return VIR_DRV_OPEN_ERROR;
        }
    }

    conn->privateData = uml_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

static int umlClose(virConnectPtr conn) {
1189 1190 1191 1192 1193
    struct uml_driver *driver = conn->privateData;

    umlDriverLock(driver);
    virDomainEventCallbackListRemoveConn(conn,
                                         driver->domainEventState->callbacks);
1194
    umlProcessAutoDestroyRun(driver, conn);
1195
    umlDriverUnlock(driver);
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206

    conn->privateData = NULL;

    return 0;
}

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


1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
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;
}


1221 1222 1223 1224
static char *umlGetCapabilities(virConnectPtr conn) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
    char *xml;

1225
    umlDriverLock(driver);
1226
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1227
        virReportOOMError();
1228
    umlDriverUnlock(driver);
1229 1230 1231 1232 1233 1234

    return xml;
}



1235 1236 1237
static int umlGetProcessInfo(unsigned long long *cpuTime, int pid)
{
    char *proc;
1238 1239 1240
    FILE *pidinfo;
    unsigned long long usertime, systime;

1241
    if (virAsprintf(&proc, "/proc/%d/stat", pid) < 0) {
1242 1243 1244 1245 1246 1247
        return -1;
    }

    if (!(pidinfo = fopen(proc, "r"))) {
        /* VM probably shut down, so fake 0 */
        *cpuTime = 0;
1248
        VIR_FREE(proc);
1249 1250 1251
        return 0;
    }

1252 1253
    VIR_FREE(proc);

1254 1255
    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");
1256
        VIR_FORCE_FCLOSE(pidinfo);
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
        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);

1269
    VIR_FORCE_FCLOSE(pidinfo);
1270 1271 1272 1273 1274 1275 1276 1277

    return 0;
}


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

1281
    umlDriverLock(driver);
1282
    vm = virDomainFindByID(&driver->domains, id);
1283 1284
    umlDriverUnlock(driver);

1285
    if (!vm) {
1286
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1287
        goto cleanup;
1288 1289 1290 1291
    }

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

cleanup:
1294 1295
    if (vm)
        virDomainObjUnlock(vm);
1296 1297
    return dom;
}
1298

1299 1300 1301
static virDomainPtr umlDomainLookupByUUID(virConnectPtr conn,
                                            const unsigned char *uuid) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1302 1303
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1304

1305
    umlDriverLock(driver);
1306
    vm = virDomainFindByUUID(&driver->domains, uuid);
1307 1308
    umlDriverUnlock(driver);

1309
    if (!vm) {
1310
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1311
        goto cleanup;
1312 1313 1314 1315
    }

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

cleanup:
1318 1319
    if (vm)
        virDomainObjUnlock(vm);
1320 1321
    return dom;
}
1322

1323 1324 1325
static virDomainPtr umlDomainLookupByName(virConnectPtr conn,
                                            const char *name) {
    struct uml_driver *driver = (struct uml_driver *)conn->privateData;
1326 1327
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1328

1329
    umlDriverLock(driver);
1330
    vm = virDomainFindByName(&driver->domains, name);
1331 1332
    umlDriverUnlock(driver);

1333
    if (!vm) {
1334
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1335
        goto cleanup;
1336 1337 1338 1339
    }

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

cleanup:
1342 1343
    if (vm)
        virDomainObjUnlock(vm);
1344 1345 1346
    return dom;
}

1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357

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) {
1358
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
        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) {
1380
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
        goto cleanup;
    }
    ret = obj->persistent;

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

1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
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) {
        umlReportError(VIR_ERR_NO_DOMAIN, NULL);
        goto cleanup;
    }
    ret = obj->updated;

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

1412
static int umlGetVersion(virConnectPtr conn, unsigned long *version) {
1413
    struct uml_driver *driver = conn->privateData;
1414
    struct utsname ut;
1415
    int ret = -1;
1416

1417
    umlDriverLock(driver);
1418 1419 1420 1421

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

1422
        if (virParseVersionString(ut.release, &driver->umlVersion, true) < 0) {
1423
            umlReportError(VIR_ERR_INTERNAL_ERROR,
1424 1425 1426
                           _("cannot parse version %s"), ut.release);
            goto cleanup;
        }
1427 1428
    }

1429 1430 1431 1432 1433 1434
    *version = driver->umlVersion;
    ret = 0;

cleanup:
    umlDriverUnlock(driver);
    return ret;
1435 1436 1437
}

static int umlListDomains(virConnectPtr conn, int *ids, int nids) {
1438
    struct uml_driver *driver = conn->privateData;
1439
    int n;
1440

1441
    umlDriverLock(driver);
1442
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
1443
    umlDriverUnlock(driver);
1444

1445
    return n;
1446 1447
}
static int umlNumDomains(virConnectPtr conn) {
1448
    struct uml_driver *driver = conn->privateData;
1449
    int n;
1450

1451
    umlDriverLock(driver);
1452
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
1453
    umlDriverUnlock(driver);
1454 1455 1456 1457

    return n;
}
static virDomainPtr umlDomainCreate(virConnectPtr conn, const char *xml,
1458
                                      unsigned int flags) {
1459
    struct uml_driver *driver = conn->privateData;
1460
    virDomainDefPtr def;
1461
    virDomainObjPtr vm = NULL;
1462
    virDomainPtr dom = NULL;
1463
    virDomainEventPtr event = NULL;
1464

1465
    virCheckFlags(VIR_DOMAIN_START_AUTODESTROY, NULL);
1466

1467
    umlDriverLock(driver);
1468
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
1469
                                        1 << VIR_DOMAIN_VIRT_UML,
1470
                                        VIR_DOMAIN_XML_INACTIVE)))
1471
        goto cleanup;
1472

1473
    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
1474
        goto cleanup;
1475

1476
    if (!(vm = virDomainAssignDef(driver->caps,
1477
                                  &driver->domains,
1478
                                  def, false)))
1479 1480
        goto cleanup;
    def = NULL;
1481

1482 1483
    if (umlStartVMDaemon(conn, driver, vm,
                         (flags & VIR_DOMAIN_START_AUTODESTROY)) < 0) {
1484
        virDomainAuditStart(vm, "booted", false);
1485 1486
        virDomainRemoveInactive(&driver->domains,
                                vm);
1487 1488
        vm = NULL;
        goto cleanup;
1489
    }
1490
    virDomainAuditStart(vm, "booted", true);
1491 1492 1493
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
1494 1495 1496

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1497 1498 1499

cleanup:
    virDomainDefFree(def);
1500 1501
    if (vm)
        virDomainObjUnlock(vm);
1502 1503
    if (event)
        umlDomainEventQueue(driver, event);
1504
    umlDriverUnlock(driver);
1505 1506 1507 1508 1509
    return dom;
}


static int umlDomainShutdown(virDomainPtr dom) {
1510 1511
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1512
    char *info = NULL;
1513
    int ret = -1;
1514

1515
    umlDriverLock(driver);
1516
    vm = virDomainFindByID(&driver->domains, dom->id);
1517
    umlDriverUnlock(driver);
1518
    if (!vm) {
1519
        umlReportError(VIR_ERR_NO_DOMAIN,
1520
                       _("no domain with matching id %d"), dom->id);
1521
        goto cleanup;
1522 1523 1524 1525
    }

#if 0
    if (umlMonitorCommand(driver, vm, "system_powerdown", &info) < 0) {
1526 1527
        umlReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("shutdown operation failed"));
1528
        goto cleanup;
1529
    }
1530
    ret = 0;
1531 1532
#endif

1533 1534
cleanup:
    VIR_FREE(info);
1535 1536
    if (vm)
        virDomainObjUnlock(vm);
1537
    return ret;
1538 1539 1540
}


1541 1542 1543 1544
static int
umlDomainDestroyFlags(virDomainPtr dom,
                      unsigned int flags)
{
1545 1546
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1547
    virDomainEventPtr event = NULL;
1548
    int ret = -1;
1549

1550 1551
    virCheckFlags(0, -1);

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

1560
    umlShutdownVMDaemon(driver, vm, VIR_DOMAIN_SHUTOFF_DESTROYED);
1561
    virDomainAuditStop(vm, "destroyed");
1562 1563 1564
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
1565
    if (!vm->persistent) {
1566 1567
        virDomainRemoveInactive(&driver->domains,
                                vm);
1568 1569 1570
        vm = NULL;
    }
    ret = 0;
1571

1572
cleanup:
1573 1574
    if (vm)
        virDomainObjUnlock(vm);
1575 1576
    if (event)
        umlDomainEventQueue(driver, event);
1577
    umlDriverUnlock(driver);
1578
    return ret;
1579 1580 1581
}


1582 1583 1584 1585 1586 1587
static int umlDomainDestroy(virDomainPtr dom)
{
    return umlDomainDestroyFlags(dom, 0);
}


1588
static char *umlDomainGetOSType(virDomainPtr dom) {
1589 1590 1591
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1592

1593
    umlDriverLock(driver);
1594
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1595
    umlDriverUnlock(driver);
1596
    if (!vm) {
1597
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1598
                       _("no domain with matching uuid"));
1599
        goto cleanup;
1600 1601
    }

1602
    if (!(type = strdup(vm->def->os.type)))
1603
        virReportOOMError();
1604 1605

cleanup:
1606 1607
    if (vm)
        virDomainObjUnlock(vm);
1608 1609 1610 1611 1612
    return type;
}

/* Returns max memory in kb, 0 if error */
static unsigned long umlDomainGetMaxMemory(virDomainPtr dom) {
1613 1614 1615
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned long ret = 0;
1616

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

1621 1622 1623 1624
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1625
        umlReportError(VIR_ERR_NO_DOMAIN,
1626 1627
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
1628
    }
1629
    ret = vm->def->mem.max_balloon;
1630

1631
cleanup:
1632 1633
    if (vm)
        virDomainObjUnlock(vm);
1634
    return ret;
1635 1636 1637
}

static int umlDomainSetMaxMemory(virDomainPtr dom, unsigned long newmax) {
1638 1639 1640
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1641

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

1646 1647 1648 1649
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1650
        umlReportError(VIR_ERR_NO_DOMAIN,
1651
                       _("no domain with matching uuid '%s'"), uuidstr);
1652
        goto cleanup;
1653 1654
    }

1655
    if (newmax < vm->def->mem.cur_balloon) {
1656 1657
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("cannot set max memory lower than current memory"));
1658
        goto cleanup;
1659 1660
    }

1661
    vm->def->mem.max_balloon = newmax;
1662 1663 1664
    ret = 0;

cleanup:
1665 1666
    if (vm)
        virDomainObjUnlock(vm);
1667
    return ret;
1668 1669 1670
}

static int umlDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
1671 1672 1673
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1674

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

1679 1680 1681 1682
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1683
        umlReportError(VIR_ERR_NO_DOMAIN,
1684
                       _("no domain with matching uuid '%s'"), uuidstr);
1685
        goto cleanup;
1686 1687
    }

D
Daniel P. Berrange 已提交
1688
    if (virDomainObjIsActive(vm)) {
1689
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
1690
                       _("cannot set memory of an active domain"));
1691
        goto cleanup;
1692 1693
    }

1694
    if (newmem > vm->def->mem.max_balloon) {
1695 1696
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("cannot set memory higher than max memory"));
1697
        goto cleanup;
1698 1699
    }

1700
    vm->def->mem.cur_balloon = newmem;
1701 1702 1703
    ret = 0;

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

static int umlDomainGetInfo(virDomainPtr dom,
                              virDomainInfoPtr info) {
1711 1712 1713 1714
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

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

1719
    if (!vm) {
1720
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1721
                       _("no domain with matching uuid"));
1722
        goto cleanup;
1723 1724
    }

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

D
Daniel P. Berrange 已提交
1727
    if (!virDomainObjIsActive(vm)) {
1728 1729 1730
        info->cpuTime = 0;
    } else {
        if (umlGetProcessInfo(&(info->cpuTime), vm->pid) < 0) {
1731 1732
            umlReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("cannot read cputime for domain"));
1733
            goto cleanup;
1734 1735 1736
        }
    }

1737 1738
    info->maxMem = vm->def->mem.max_balloon;
    info->memory = vm->def->mem.cur_balloon;
1739
    info->nrVirtCpu = vm->def->vcpus;
1740 1741 1742
    ret = 0;

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


1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770
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) {
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
        goto cleanup;
    }

J
Jiri Denemark 已提交
1771
    *state = virDomainObjGetState(vm, reason);
1772 1773 1774 1775 1776 1777 1778 1779 1780
    ret = 0;

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


1781
static char *umlDomainGetXMLDesc(virDomainPtr dom,
E
Eric Blake 已提交
1782 1783
                                 unsigned int flags)
{
1784 1785 1786 1787
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;

1788
    /* Flags checked by virDomainDefFormat */
E
Eric Blake 已提交
1789

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

1794
    if (!vm) {
1795
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1796
                       _("no domain with matching uuid"));
1797
        goto cleanup;
1798 1799
    }

1800
    ret = virDomainDefFormat((flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
1801 1802 1803 1804
                             vm->newDef : vm->def,
                             flags);

cleanup:
1805 1806
    if (vm)
        virDomainObjUnlock(vm);
1807
    return ret;
1808 1809 1810 1811 1812
}


static int umlListDefinedDomains(virConnectPtr conn,
                            char **const names, int nnames) {
1813
    struct uml_driver *driver = conn->privateData;
1814
    int n;
1815

1816
    umlDriverLock(driver);
1817
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
1818
    umlDriverUnlock(driver);
1819

1820
    return n;
1821 1822 1823
}

static int umlNumDefinedDomains(virConnectPtr conn) {
1824
    struct uml_driver *driver = conn->privateData;
1825
    int n;
1826

1827
    umlDriverLock(driver);
1828
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
1829
    umlDriverUnlock(driver);
1830 1831 1832 1833 1834

    return n;
}


1835
static int umlDomainStartWithFlags(virDomainPtr dom, unsigned int flags) {
1836 1837
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1838
    virDomainEventPtr event = NULL;
1839
    int ret = -1;
1840

1841
    virCheckFlags(VIR_DOMAIN_START_AUTODESTROY, -1);
1842

1843
    umlDriverLock(driver);
1844
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1845

1846
    if (!vm) {
1847
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1848
                       _("no domain with matching uuid"));
1849
        goto cleanup;
1850 1851
    }

1852 1853
    ret = umlStartVMDaemon(dom->conn, driver, vm,
                           (flags & VIR_DOMAIN_START_AUTODESTROY));
1854
    virDomainAuditStart(vm, "booted", ret >= 0);
1855 1856 1857 1858
    if (ret == 0)
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED);
1859 1860

cleanup:
1861 1862
    if (vm)
        virDomainObjUnlock(vm);
1863 1864
    if (event)
        umlDomainEventQueue(driver, event);
1865
    umlDriverUnlock(driver);
1866
    return ret;
1867 1868
}

1869 1870 1871
static int umlDomainStart(virDomainPtr dom) {
    return umlDomainStartWithFlags(dom, 0);
}
1872 1873

static virDomainPtr umlDomainDefine(virConnectPtr conn, const char *xml) {
1874
    struct uml_driver *driver = conn->privateData;
1875
    virDomainDefPtr def;
1876
    virDomainObjPtr vm = NULL;
1877
    virDomainPtr dom = NULL;
1878

1879
    umlDriverLock(driver);
1880
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
1881
                                        1 << VIR_DOMAIN_VIRT_UML,
1882
                                        VIR_DOMAIN_XML_INACTIVE)))
1883
        goto cleanup;
1884

1885 1886 1887
    if (virDomainObjIsDuplicate(&driver->domains, def, 0) < 0)
        goto cleanup;

1888
    if (!(vm = virDomainAssignDef(driver->caps,
1889
                                  &driver->domains,
1890
                                  def, false)))
1891 1892
        goto cleanup;
    def = NULL;
1893 1894
    vm->persistent = 1;

1895
    if (virDomainSaveConfig(driver->configDir,
1896 1897 1898
                            vm->newDef ? vm->newDef : vm->def) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1899
        vm = NULL;
1900
        goto cleanup;
1901 1902 1903 1904
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;
1905 1906 1907

cleanup:
    virDomainDefFree(def);
1908 1909 1910
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1911 1912 1913
    return dom;
}

1914 1915 1916
static int umlDomainUndefineFlags(virDomainPtr dom,
                                  unsigned int flags)
{
1917 1918 1919
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1920

1921 1922
    virCheckFlags(0, -1);

1923
    umlDriverLock(driver);
1924
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1925
    if (!vm) {
1926
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
1927
                       _("no domain with matching uuid"));
1928
        goto cleanup;
1929 1930 1931
    }

    if (!vm->persistent) {
1932
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
1933
                       _("cannot undefine transient domain"));
1934
        goto cleanup;
1935 1936
    }

1937
    if (virDomainDeleteConfig(driver->configDir, driver->autostartDir, vm) < 0)
1938
        goto cleanup;
1939

1940 1941 1942 1943 1944 1945 1946
    if (virDomainObjIsActive(vm)) {
        vm->persistent = 0;
    } else {
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
    }

1947
    ret = 0;
1948

1949
cleanup:
1950 1951 1952
    if (vm)
        virDomainObjUnlock(vm);
    umlDriverUnlock(driver);
1953
    return ret;
1954 1955 1956
}


1957 1958 1959 1960 1961
static int umlDomainUndefine(virDomainPtr dom)
{
    return umlDomainUndefineFlags(dom, 0);
}

1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 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 2066 2067 2068 2069
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)) {
            umlReportError(VIR_ERR_OPERATION_FAILED,
                           _("target %s already exists"), disk->dst);
            return -1;
        }
    }

    if (!disk->src) {
        umlReportError(VIR_ERR_INTERNAL_ERROR,
                       "%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);
        umlReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
        umlReportError(VIR_ERR_OPERATION_INVALID,
                       "%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 {
            umlReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("disk bus '%s' cannot be hotplugged."),
                           virDomainDiskBusTypeToString(dev->data.disk->bus));
        }
    } else {
        umlReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("device type '%s' cannot be attached"),
                       virDomainDeviceTypeToString(dev->type));
        goto cleanup;
    }

cleanup:

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


2070 2071 2072 2073 2074 2075 2076
static int
umlDomainAttachDeviceFlags(virDomainPtr dom,
                           const char *xml,
                           unsigned int flags)
{
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG, -1);

2077
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 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
        umlReportError(VIR_ERR_OPERATION_INVALID,
                       "%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) {
        umlReportError(VIR_ERR_OPERATION_FAILED,
                       _("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);
        umlReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
        umlReportError(VIR_ERR_OPERATION_INVALID,
                       "%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 {
            umlReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("This type of disk cannot be hot unplugged"));
        }
    } else {
        umlReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       "%s", _("This type of device cannot be hot unplugged"));
    }

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


2182 2183 2184 2185 2186 2187 2188
static int
umlDomainDetachDeviceFlags(virDomainPtr dom,
                           const char *xml,
                           unsigned int flags)
{
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG, -1);

2189
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
2190 2191 2192 2193 2194 2195 2196 2197
        umlReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    return umlDomainDetachDevice(dom, xml);
}

2198 2199 2200

static int umlDomainGetAutostart(virDomainPtr dom,
                            int *autostart) {
2201 2202 2203
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2204

2205
    umlDriverLock(driver);
2206
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2207

2208
    if (!vm) {
2209
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
2210
                       _("no domain with matching uuid"));
2211
        goto cleanup;
2212 2213 2214
    }

    *autostart = vm->autostart;
2215
    ret = 0;
2216

2217
cleanup:
2218 2219
    if (vm)
        virDomainObjUnlock(vm);
2220
    umlDriverUnlock(driver);
2221
    return ret;
2222 2223 2224 2225
}

static int umlDomainSetAutostart(virDomainPtr dom,
                                   int autostart) {
2226
    struct uml_driver *driver = dom->conn->privateData;
2227
    virDomainObjPtr vm;
2228 2229 2230
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

2231 2232 2233
    umlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

2234
    if (!vm) {
2235
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
2236
                       _("no domain with matching uuid"));
2237
        goto cleanup;
2238 2239 2240
    }

    if (!vm->persistent) {
2241
        umlReportError(VIR_ERR_OPERATION_INVALID, "%s",
2242
                       _("cannot set autostart for transient domain"));
2243
        goto cleanup;
2244 2245 2246 2247
    }

    autostart = (autostart != 0);

2248
    if (vm->autostart != autostart) {
2249
        if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
2250
            goto cleanup;
2251
        if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
2252
            goto cleanup;
2253

2254
        if (autostart) {
2255 2256
            if (virFileMakePath(driver->autostartDir) < 0) {
                virReportSystemError(errno,
2257 2258
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
2259 2260
                goto cleanup;
            }
2261

2262
            if (symlink(configFile, autostartLink) < 0) {
2263
                virReportSystemError(errno,
2264 2265
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
2266 2267 2268 2269
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
2270
                virReportSystemError(errno,
2271 2272
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
2273 2274
                goto cleanup;
            }
2275 2276
        }

2277
        vm->autostart = autostart;
2278 2279 2280 2281 2282 2283
    }
    ret = 0;

cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
2284 2285
    if (vm)
        virDomainObjUnlock(vm);
2286
    umlDriverUnlock(driver);
2287 2288 2289 2290 2291
    return ret;
}


static int
2292 2293 2294 2295
umlDomainBlockPeek(virDomainPtr dom,
                   const char *path,
                   unsigned long long offset, size_t size,
                   void *buffer,
E
Eric Blake 已提交
2296
                   unsigned int flags)
2297
{
2298 2299
    struct uml_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2300 2301
    int fd = -1, ret = -1;
    const char *actual;
2302

E
Eric Blake 已提交
2303 2304
    virCheckFlags(0, -1);

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

2309
    if (!vm) {
2310
        umlReportError(VIR_ERR_NO_DOMAIN, "%s",
2311
                       _("no domain with matching uuid"));
2312
        goto cleanup;
2313 2314 2315
    }

    if (!path || path[0] == '\0') {
2316 2317
        umlReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("NULL or empty path"));
2318
        goto cleanup;
2319 2320 2321
    }

    /* Check the path belongs to this domain. */
2322 2323 2324 2325
    if (!(actual = virDomainDiskPathByName(vm->def, path))) {
        umlReportError(VIR_ERR_INVALID_ARG,
                       _("invalid path '%s'"), path);
        goto cleanup;
2326
    }
2327
    path = actual;
2328

2329 2330 2331 2332 2333 2334 2335
    /* 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;
    }
2336

2337 2338 2339 2340 2341 2342 2343 2344 2345
    /* 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;
2346 2347
    }

2348 2349
    ret = 0;

2350
cleanup:
2351
    VIR_FORCE_CLOSE(fd);
2352 2353
    if (vm)
        virDomainObjUnlock(vm);
2354 2355 2356 2357
    return ret;
}


2358 2359
static int
umlDomainOpenConsole(virDomainPtr dom,
2360
                     const char *dev_name,
2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386
                     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;

    virCheckFlags(0, -1);

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

    if (!virDomainObjIsActive(vm)) {
        umlReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

2387
    if (dev_name) {
2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400
        /* XXX support device aliases in future */
        umlReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Named device aliases are not supported"));
        goto cleanup;
    } else {
        if (vm->def->console)
            chr = vm->def->console;
        else if (vm->def->nserials)
            chr = vm->def->serials[0];
    }

    if (!chr) {
        umlReportError(VIR_ERR_INTERNAL_ERROR,
2401
                        _("cannot find character device %s"), dev_name);
2402 2403 2404
        goto cleanup;
    }

2405
    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
2406
        umlReportError(VIR_ERR_INTERNAL_ERROR,
2407
                        _("character device %s is not using a PTY"), dev_name);
2408 2409 2410
        goto cleanup;
    }

2411
    if (virFDStreamOpenFile(st, chr->source.data.file.path,
E
Eric Blake 已提交
2412
                            0, 0, O_RDWR) < 0)
2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
        goto cleanup;

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

2423

2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 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 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532
static int
umlDomainEventRegister(virConnectPtr conn,
                       virConnectDomainEventCallback callback,
                       void *opaque,
                       virFreeCallback freecb)
{
    struct uml_driver *driver = conn->privateData;
    int ret;

    umlDriverLock(driver);
    ret = virDomainEventCallbackListAdd(conn,
                                        driver->domainEventState->callbacks,
                                        callback, opaque, freecb);
    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);
    ret = virDomainEventCallbackListAddID(conn,
                                          driver->domainEventState->callbacks,
                                          dom, eventID,
                                          callback, opaque, freecb);
    umlDriverUnlock(driver);

    return ret;
}


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

    umlDriverLock(driver);
    ret = virDomainEventStateDeregisterAny(conn,
                                           driver->domainEventState,
                                           callbackID);
    umlDriverUnlock(driver);

    return ret;
}


static void umlDomainEventDispatchFunc(virConnectPtr conn,
                                       virDomainEventPtr event,
                                       virConnectDomainEventGenericCallback cb,
                                       void *cbopaque,
                                       void *opaque)
{
    struct uml_driver *driver = opaque;

    /* Drop the lock whle dispatching, for sake of re-entrancy */
    umlDriverUnlock(driver);
    virDomainEventDispatchDefaultFunc(conn, event, cb, cbopaque, NULL);
    umlDriverLock(driver);
}


static void umlDomainEventFlush(int timer ATTRIBUTE_UNUSED, void *opaque)
{
    struct uml_driver *driver = opaque;

    umlDriverLock(driver);
    virDomainEventStateFlush(driver->domainEventState,
                             umlDomainEventDispatchFunc,
                             driver);
    umlDriverUnlock(driver);
}


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



2533
static virDriver umlDriver = {
2534 2535
    .no = VIR_DRV_UML,
    .name = "UML",
2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550
    .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 */
    .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 */
    .domainDestroy = umlDomainDestroy, /* 0.5.0 */
2551
    .domainDestroyFlags = umlDomainDestroyFlags, /* 0.9.4 */
2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564
    .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 */
2565
    .domainUndefineFlags = umlDomainUndefineFlags, /* 0.9.4 */
2566 2567 2568 2569 2570 2571 2572
    .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 */
2573
    .nodeGetCPUStats = nodeGetCPUStats, /* 0.9.3 */
2574
    .nodeGetMemoryStats = nodeGetMemoryStats, /* 0.9.3 */
2575 2576
    .nodeGetCellsFreeMemory = nodeGetCellsFreeMemory, /* 0.5.0 */
    .nodeGetFreeMemory = nodeGetFreeMemory, /* 0.5.0 */
2577 2578
    .domainEventRegister = umlDomainEventRegister, /* 0.9.4 */
    .domainEventDeregister = umlDomainEventDeregister, /* 0.9.4 */
2579 2580 2581 2582 2583
    .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 */
2584 2585
    .domainEventRegisterAny = umlDomainEventRegisterAny, /* 0.9.4 */
    .domainEventDeregisterAny = umlDomainEventDeregisterAny, /* 0.9.4 */
2586
    .domainOpenConsole = umlDomainOpenConsole, /* 0.8.6 */
2587 2588
};

2589 2590 2591 2592 2593 2594 2595 2596
static int
umlVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
                   virHashIterator iter, void *data)
{
    virHashForEach(uml_driver->domains.objs, iter, data);

    return 0;
}
2597 2598

static virStateDriver umlStateDriver = {
2599
    .name = "UML",
2600 2601 2602 2603 2604 2605
    .initialize = umlStartup,
    .cleanup = umlShutdown,
    .reload = umlReload,
    .active = umlActive,
};

2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617
static void
umlVMDriverLock(void)
{
    umlDriverLock(uml_driver);
}

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

2618 2619 2620
static virNWFilterCallbackDriver umlCallbackDriver = {
    .name = "UML",
    .vmFilterRebuild = umlVMFilterRebuild,
2621 2622
    .vmDriverLock = umlVMDriverLock,
    .vmDriverUnlock = umlVMDriverUnlock,
2623 2624
};

2625 2626 2627
int umlRegister(void) {
    virRegisterDriver(&umlDriver);
    virRegisterStateDriver(&umlStateDriver);
2628
    virNWFilterRegisterCallbackDriver(&umlCallbackDriver);
2629 2630
    return 0;
}